Read and write operation Flow:
1. Define a Stream object for the file to be manipulated.
2. Open (Create) the file.
3. Perform read and write operations.
4. Close the file.
Detailed
1. Create a Stream object:
Input file Stream Class (perform read operation): Ifstream in;
Output file Stream class (perform write operation): Ofstream out;
Input output file Stream class: FStream both;
Note: These three types of file stream classes are defined in FStream, so just add FStream to the header file.
2. Open the function using the member function:
How to use: Ios::in Open File as input (read operation)
Ios::out Open the file as output (write operation), if there is already a folder of this name, the original content of all clear
Ios::app opening a file as input, and writing data to the end of the file
Ios::ate open a file, move the file pointer to the end of the file
Ios::binary open a file in binary mode, default to text open mode
Example: Defining a Stream Class object: Ofstream out (output stream)
Write operation: Out.open ("Test.dat", ios::out); Open a question named Test.dat.
3. Read and write text files:
(1) write the string Hello world to the disk file Test.dat
#include <iostream>#include<fstream>using namespacestd;intMain () {Ofstream fout ("Test.dat"Ios:: out); if(!fout) {cout<<"File open failed! "<<Endl; Exit (1); } fout<<"Hello World"; Fout.close (); return 0; Checking the file Test.dat will find the contents of the file as Hello world
(2) Read the files in the Test.dat and display them on the screen.
#include <iostream>#include<fstream>using namespacestd;intMain () {ifstream fin ("Test.dat"Ios::inch); if(!Fin) {cout<<"File open failed! "<<Endl; Exit (1); } Charstr[ -]; Fin.getline (str, -) cout<<str<<Endl; Fin.close (); return 0; }
4. Closing the file:
Stream object. Close (); No parameters
C + + file read and write operations