How to use Ofstream-super fine. C + + file write, read out function

Source: Internet
Author: User

How to use Ofstream
Ofstream is from the memory to the hard disk, Ifstream is from the hard disk to the memory, actually the so-called stream buffer is the memory space;
In C + +, there is a stream in this class, all I/O is based on this "stream" class, including the files we want to know i/o,stream this class has two important operators:
1. Insertion device (<<)
Outputs data to the stream. For example, the system has a default standard output stream (cout), usually refers to the display, so,cout<< "write Stdout" << ' \ n '; means the string "write Stdout" and the newline character (' \ n ') Output to the standard output stream.
2. Extraction Device (>>)
Enter data from the stream. For example, the system has a default standard input stream (CIN), which is normally referred to as the keyboard, so,cin>>x; is the data that reads a specified type (that is, the type of the variable x) from the standard input stream.
In C + +, the operation of the file is implemented through the subclass FStream (file stream) of the stream, so to manipulate the file in this way, the header file fstream.h must be added. The following is the process of this type of file operation one by one.
First, open the file
In the FStream class, there is a member function open (), which is used to open the file, and its prototype is:
void Open (const char* filename,int mode,int access);
Parameters:
FileName: The file name to open
Mode: How to open a file
Access: Open the properties of a file
The way you open a file is defined in class iOS (the base class for all streaming I/O classes) and the values that are commonly used are as follows:
Ios::app: Open file in Append mode
Ios::ate: The file is opened and positioned to the end of the file, Ios:app contains this property
Ios::binary: Open the file in binary mode, the default way is text mode. The difference between the two methods is shown in the previous article
Ios::in: File opens in input mode (file data input to memory)
Ios::out: File opens in output mode (memory data output to file)
Ios::nocreate: Do not create file, so file does not exist when open failed
Ios::noreplace: Do not overwrite file, so if file exists failure when opening file
Ios::trunc: If the file exists, set the file length to 0
You can use "or" to connect the above attributes, such as Ios::out|ios::binary.
The properties of the open file are values:
0: Normal file, open access
1: Read-only files
2: Implied file
4: System files
You can use "or" or "+" to connect the above properties, such as 3 or 1|2 to open the file with read-only and implied properties.
Example: Opening a file as a binary input C:\Config.sys
FStream file1;
File1.open ("C:\\config.sys", ios::binary|ios::in,0);
If the open function has only one parameter for the file name, it is opened with a read/write normal file, namely:
File1.open ("C:\\config.sys"); <=> File1.open ("C:\\config.sys", ios::in|ios::out,0);
In addition, FStream also has the same constructor as open (), and for the above example, you can open the file when you define it:
FStream file1 ("C:\\config.sys");
In particular, FStream has two subclasses: ifstream (input file stream) and Ofstream (OUTPU file stream), and Ifstream opens the file as input by default. Ofstream, by default, opens the file in the output mode. Ifstream file2 ("C:\\pdos.def");//Open file as input
Ofstream file3 ("c:\\x.123");//Open file in output mode
Therefore, in the actual application, according to the needs of different, choose different classes to define: If you want to open in the input mode, use Ifstream to define, if you want to open in the output, use Ofstream to define; If you want to open with input/output mode, use FStream to set

Second, close the file
Open files must be closed after use, FStream provides a member function close () to complete this operation, such as: File1.close (), the file1 connected file is closed.
Iii. Read and write files
Read and write files are divided into text files and binary files read, for the text file reading is relatively simple, with the insertion and the profiler can be, and for the binary reading is more complicated, the next to the detailed introduction of these two ways
1. Reading and writing of text files
Reading and writing text files is simple: Use the plug-in (<<) to output to the file, and use the Profiler (>>) to import from the file. Suppose the file1 is opened as input, File2 is opened with output. Examples are as follows:
file2<< "I love You";//write The string "I love You" to the file
int i;
file1>>i;//Enter an integer value from the file.
This way there is a simple format, such as the output can be specified as 16 and so on, the specific format has the following
operator function input/output
Dec formatted as decimal numeric data input and output
Endl outputs a newline character and refreshes the stream output.
Ends output a null character output
Hex formatted as hexadecimal numeric data input and output
Oct formatted as octal numeric data input and output
setpxecision (int p) Sets the precision bit output of a floating-point number
For example, to use 123 as a hexadecimal output:file1<2. Read and write binary files
①put ()
The put () function writes a character to the stream, and its prototype is Ofstream &put (char ch), which is simpler to use, such as File1.put (' C '), which is to write a character ' C ' to the stream.
②get ()
The Get () function is more flexible and has 3 commonly used overloaded forms:
One is the form that corresponds to the put (): Ifstream &get (char &ch), the function is to read a character from the stream, the result is saved in the reference CH, if the end of the file, the null character is returned. such as File2.get (x); indicates that a character is read from a file and the read word is characters in X.
Another overloaded form of the prototype is: int get (); This form returns a character from the stream, if it reaches the end of the file, it returns EOF, such as X=file2.get (), and the previous example function is the same.
Another form of prototyping is: Ifstream &get (char *buf,int num,char delim= ' \ n '), which reads characters into an array pointed to by BUF until NUM characters are read or a character specified by Delim is encountered. If you do not use the Delim parameter, the default newline character ' \ n ' will be used. For example:
File2.get (str1,127, ' A '); Reads a character from a file to a string str1, terminating when the character ' A ' is encountered or 127 characters are read.
③ read and write data blocks
To read and write binary data blocks, use the member function read () and the Write () member functions, which are prototyped as follows: Read (unsigned char *buf,int num);
Write (const unsigned char *buf,int num);
Read () reads num characters from a file into the cache pointed to by buf, and if it is at the end of the file when NUM characters have not been read, you can use the member function int gcount () to get the number of characters actually read, while write () writes NUM characters from the cache pointed to by BUF to a file , it is important to note that the type of cache is unsigned char *, which may sometimes require a type conversion.
Cases:
unsigned char str1[]= "I love You";
int n[5];
Ifstream in ("xxx.xxx");
Ofstream out ("yyy.yyy");
Out.write (Str1,strlen (STR1));//write the string str1 all to Yyy.yyy
In.read ((unsigned char*) n,sizeof (n));//Read the specified integer from the xxx.xxx, note the type conversion
In.close (); Out.close ();
Iv. Detection of EOF
The member function EOF () is used to detect whether the end of the file is reached, or 0 if the end of the file returns a value other than 0. The prototype is an int eof ();
Example: if (in.eof ()) ShowMessage ("has reached the end of the file!") ");
V. Positioning of documents
Unlike the C file operation, the C + + I/O system manages two pointers that are associated with a file. One is a read pointer, which shows the position of the input operation in the file, and the other is the position of the write pointer, which is the next write operation. Each time the input or output is executed, the corresponding pointer changes automatically. Therefore, C + + file positioning is divided into read position and write location, corresponding member functions are SEEKG () and SEEKP (). SEEKG () is the set read position, SEEKP is the set write position. Their most common form is as follows:
IStream &AMP;SEEKG (Streamoff offset,seek_dir origin);
Ostream &AMP;SEEKP (Streamoff offset,seek_dir origin);
Streamoff, defined in iostream.h, defines the maximum value that offset offset can achieve, Seek_dir represents the base position of the move, and is an enumeration with the following values:
Ios::beg: File Start
Ios::cur: File Current Location
Ios::end: End of File
These two functions are typically used in binary files because the text file may be different from the expected value because the system interprets the characters. Cases:
FILE1.SEEKG (1234,ios::cur); Move the read pointer of a file back 1234 bytes from the current position
FILE2.SEEKP (1234,ios::beg); Move the file's write pointer back 1234 bytes from the beginning of the file
The use of FStream

Open a file
FStream F;
F.open ("1.txt", Ios::in | ios::binary);
if (!f.is_open ())//Check whether the file opened successfully
cout << "Cannot open file." << Endl;
Both Ios::in and ios::bianry are int, which defines how the file opens.
Ios::in--Open file for reading.
Ios::out--Open file is used for writing, if the file does not exist, a new one exists, and the contents are emptied.
Ios::binary-Read and write in binary bit stream, default is Ios::text, but it is better to specify this way of reading and writing, even if you want to read and write text. Because in Ios::text mode, the ' \ n ' character is converted to two characters at write time: the carriage return + newline (hex:0d 0A) is written, and the read-in is reversed, which can easily cause unnecessary trouble. Ios::app--Open file is written at the end of the file, even if you use SEEKP to change the write location, it will still be written at the end of the file.
Ios::ate--The open file is written at the end of the file, but SEEKP is valid.
Changes in read and write locations
F.SEEKG (0, Ios::beg); Change read-in position G mean Get
F.SEEKP (0, Ios::end); Change write position P mean Put
The first parameter is offset (long), and the second argument is the position of offset relative to three values:
Ios::beg--File header Ios::end--End of file Ios::cur--current position

File read/write
Char s[50];
F.read (S, 49);
S[50] = ' + '; Note that you want to add the string terminator yourself
char *s = "Hello";
F.write (S, strlen (s));
Add remember to close the file with F.close () after reading and writing.
For example, the following program deletes line numbers in the source program with line numbers.
#include
#include
using namespace Std;
Defines the format of the line number to be deleted, as defined by the type: #0001 line number
const int line_num_length = 5;
const char Line_num_start = ' # ';
int main (int argc, char *argv[])
{
FStream F;
char *s = NULL;
int n;
for (int i = 1; i < argc; i++) {
cout << "Processing file" << Argv[i] << "...";
F.open (Argv[i], ios::in | ios::binary);
if (!f.is_open ()) {
cout << "Cannot OPEN" << Endl;
Continue
}
F.SEEKG (0, Ios::end);
n = f.tellg (); File size
s = new char[n+1];
F.SEEKG (0, Ios::beg);
F.read (s, N);
S[n] = ' + ';
F.close ();
Using a simple judgment, encounter Line_num_start followed by a number,
It is considered to be a line number.
for (int j = 0; J < N; j + +) {
if (s[j] = = Line_num_start && (s[j+1] >= ' 0 ' && s[j+1] <= ' 9 ')) {
for (int k = J; k < J + Line_num_length; k++)
S[k] = ";
}
}
F.open (Argv[i], ios::out | ios::binary);
if (!f.is_open ()) {
cout << "Cannot OPEN" << Endl;
Delete[] s;
Continue
}
F.write (s, N);
F.close ();
cout << "OK" << Endl;
Delete[] s;
}
return 0;
}

How to use Ofstream-super fine. C + + file write, read out function (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.