As Objective C ++ said: C ++ is a language Federation. He is a versatile player. There are often many solutions to the same problem. The programmer should choose the solution. Therefore, this article divides the C ++ file IO into two aspects: C mode and C ++ mode. Programmers can select an appropriate and unified Io method based on their own teams.
I. Basic Knowledge 1.1 file types: ASCII files and binary files
First, I do not guarantee that there are only these two types of files. However, understanding these two types of files is very important for learning file IO operations.
1.1.1ascii File
An ASCII file is a text file. Each byte stores an ascii code, representing a character. You can open it in any editor, such as NotePad or UE. Opening is a character you can understand. For example, the name "Richard" is stored as 7 bytes, each of which is the ASCII code of the corresponding letter. The integer 10000 is saved as "10000", and each byte is the ASCII code of each letter, that is, 00110001 00110000 00110000 00110000. ASCII files are usually suitable for people to see. They are mostly used for presentation to people, so they are called text files.
1.1.2 binary file
The data in the memory is output to the disk as it is stored in the memory. The data in the memory is the various values in the program we write. For example, if I define int A = 10000, what does a look like in memory? A is an int type, with 32 characters occupying 4 Bytes: 00000000 00000000 01000111. This is the form of A in memory. It is a binary file to store this form as is. As shown in. Generally, the intermediate result data needs to be temporarily stored in the external village, and later needs to be input into the memory. Commonly used binary files are saved.
1.2 buffer and non-buffer file systems
To be improved.
1.3 What are included in all files?
A file not only contains content. You can observe what a file has in the file type in C language:
Typedef struct {
Short level;/* the degree to which the buffer is "full" or "empty */
Unsigned flags;/* File status flag */
Char FD;/* file descriptor */
Unsigned char hold;/* do not read characters without a buffer */
Short bsize;/* buffer size */
Unsigned char * buffer;/* Data Buffer position */
Unsigned char * CURP;/* pointer, current point */
Unsigned istemp;/* temporary file, indicator */
Short token;/* used for validity check */
}
The original file must contain so much information. Focus on the pointer variable CURP. It is like a cursor that comes with a file. After reading and writing from the file, the cursor moves backward. To facilitate next read/write.
1.4 how to open a file
R, W, A, Rb, WB, AB, R +, W +, A +, RB +, WB +, AB +
All binary files with B are read and written, but non-ASCII files are read and written.
To be improved.
II. c file IO
In C language, I/O is processed mainly through various functions, and the parameters of these functions are usually a file pointer.
2.1 open the file (fopen function)
File * FP;
Fp = fopen (file name, open mode );
Sample Code:
If (FP = fopen ("./file1", "R") = NULL ){
Printf ("cannot open this file \ n ");
Exit (0 );
}
2.2 close a file (fclose function)
Close the file after use
Fclose (File pointer );
Code example: fclose (FP );
2.3 file read/write 2.3.1 fputc function and fgetc function (putc function and GETC function)
Fputc (CH, FP); writes a letter ch to the file pointer FP.
Ch = fgetc (FP); The read character is assigned to Ch.
2.3.2 fread and fwrite Functions
The fgetc and fputc functions can be used to read and write a character in a file. But it is often required to read a group of data at a time (for example, a real number or a struct variable ). This requires fread and fwrite to read and write a data block.
Fread (buffer, size, Count, FP );
Fwrite (buffer, size, Count, FP );
Fread and fwrite functions are generally used for input and output of binary files. Because they process the input and output according to the length of the data block. Note This when writing and reading are required. Those who have suffered losses in this aspect have a deep understanding of the principles.
2.3.3 fprintf and fscanf
In this case, I store the student data in a file for later reference. Note that the student data should be shown to others. Fread and fwrite can read and write data blocks such as struct. But as mentioned above, the suitable binary file can be read and written. It is not suitable for viewing ASCII files.
Struct student {
Int ID;
Char name [15];
Char ADDR [15];
Int age;
};
Int main (){
Struct student lily = {1234, "Li", "Shaanxi", 20 };
File * FP;
If (FP = fopen ("studentstable", "WB") = NULL ){
Printf ("% s \ n", "error ");
Return 0;
}
Fwrite (& Lily, sizeof (struct student), 1, FP );
Fclose (FP );
Return 0;
}
After executing this code, open studentstable and find that all except the middle lishaanxi are binary 1, 0. it cannot be identified because it stores 32-bit binary values of integers 1234 and 20 in the memory. Of course, it cannot be recognized, and the char type is a byte in memory and ASCII files and binary files. Displayed. Human identification. So you can see the result after opening the binary file studentstable.
Therefore, if you want to read and write student data in an ASCII file, you can use fread and fwrite to open studentstable in an ASCII file. even if the written result is 1234lishaanxi20. (Errors often occur ). You can see how difficult it is to differentiate the data. Therefore, we need to be able to format the output data to a file, such as 1234 | Li | Shaanxi | 20. Fprintf and fscanf will be used at this time.
Fprintf (File pointer, Format String, output list );
Fsacnf (File pointer, Format String, input list );
The code can be improved:
If (FP = fopen ("studentstable", "W") = NULL ){
Printf ("% s \ n", "error ");
Return 0;
}
Fprintf (FP, "% d | % S | % d", Lily. ID, Lily. Name, Lily. ADDR, Lily. Age );
After opening the studentstable file, you will see 1234 | Li | Shaanxi | 20.
Of course, fsacnf is to read files in the corresponding format.
2.3.4 other functions
Putw, getw, fgets, fputs. These functions will be used only after you have mastered the above. That's not enough.
2.4 File Location
As described in the basic section above, the file has a position pointer pointing to the current read/write position. If you read and write a file sequentially and each time you read and write a character, after you write a character, the pointer automatically moves to the next character position. If you want to change this rule and force the position pointer to another specified position, you can use the following function.
Rewind, fseek, ftell, etc.
III. C ++ file IO
In addition to the file I/O function of C, C ++ also provides an object-oriented processing method. The I/O Stream class library is used. Remember this figure before learning C ++ file IO. This is very important. Here, stream is not explained. I indicates in, O indicates out, and F indicates file.
3.1 learn new things 3.1.1 tips
"CIN>", "cout <" has been used. In fact, CIN is an object of the istream class, And cout is an object of the ostram class. As for "<", ">", it is only the heavy-duty operators of these two classes. Because "<", ">" is just a flow, just like a flow. For example, CIN> A; From CIN to A, that is, from standard input to keyboard input to variable A. Isn't that from keyboard input assigned to. Another example is cout <A; A flows from A to cout, that is, the standard output flows from variable A to display its screen. Isn't it just printing a to the screen. In this way, the objects of istream, ostream, and their subclasses can all use "<" or "> ".
3.1.2 standard output (screen output) and standard input (keyboard input)
Stream object <operations
Stream object. Put (char C );
Stream object. wirte (const char * STR, int N );
Stream Object> operations
Stream object. Get ();
Stream object. Get (char C );
Stream object. Getline (char * Buf, int N, char Deline = '\ n ');
Stream object. Read (char * Buf, int size );
Note that most of the above Stream object operations except get () return the reference of the current stream object, which can be used continuously. For example, cout <A <B <C, cout. Put (a). Put (B), Cin. Get (a). Get (C );
3.2 Open and Close operations for files 3.2.1 open a file
A) how to open a file using a fstream object
Fstream <Object Name>
<Object Name>. Open ("<File Name>", <method> );
Method: Io, out, app, ate, binary ...... IOS: In | IOs: Out, IOS: Out | IOs: Binary ......
Example:
Open a text file by writing
Fstream OUTFILE;
OUTFILE. Open ("file.txt", IOS: Out)
Or fstream OUTFILE ("file.txt", IOS: Out)
Open the binary data file. dat in Read mode
Fstream infile ("file. dat", IOS: Binary | in );
B) how to open a file using an ofstream or ifstream object
Ofstream <Object Name>
<Object Name>. Open ("<File Name> ")
Why is there no way to open this item? Because the output stream is already specified. You do not need to tell whether to write or read it.
Example:
Ofstream out1;
Out1.open ("file. cpp ");
Or ofstream out1 ("file. cpp ");
Ifsteam in1;
In1.open ("file1.cpp ");
Or ifstream in1 ("file1.cpp ")
3.2.2 disable a file
<Stream Object Name>. Close ();
Example: out1.close ();
3.3 read/write operations on text files
Since cout and CIN are ofstream and ifstream objects, their methods also apply to our file streams. So easy.
3.4 binary file read/write operations
Same as above.
3.5 format Control
There are too many Stream object format control functions. You can query them when necessary.
3.6 random read/write
Random read/write is equivalent to the location of a file in the C language. You can change the cursor in the file. The stream object is related to these methods. Learn as you go.