Generally, the open () and close () member functions defined in the fstream class are used ().
Fstream OUTFILE; defines an object of the fstream class.
OUTFILE. Open ("f1.txt", IOS: Out );
Or fstream OUTFILE ("f1.txt", IOS: Out );
In open the file as input (read)
Open the file in output (write) Mode
The app opens the file as an output append
When the ATE file is opened, the file pointer is located at the end of the file
Trune if the file exists, truncates it to 0 and clears the original
Content. If the file does not exist, a new file is created.
Binary opens a file in binary mode. The default value is text mode.
Nocreate open an existing file. If the file does not exist, it fails to be opened.
If a file exists in noreplace
Opening operation failed
IOS: In | IOs: out open a file in Read and Write mode
IOS: Out | IOs: Binary open a file in binary write mode
IOS: In | IOs: Binary open a file in binary read mode
If binary mode is not specified, files are opened in text mode. If binary mode is specified, files are opened in binary mode.
Another way to open a file is to use fstream's specialized read or write subclass.
Ofstream OUTFILE ("f1.txt", IOS: Out); write
Ifstream istrm ("f2.txt"); read
Do not forget to close the file after reading it.
Infile. Close ();
//
For example:
The main class for reading and writing files in MFC is cfile, while the cstdiofile class is derived from the cfile class. It mainly adds the function of reading/writing strings in each row of files in a row! Nothing else to study!
// Cfile reads all files to the buffer zone:
Cfile file;
Char buffer [1024];
If (! File. Open ("C: // aaa.txt", cfile: moderead) return; // open the file AAA in the form of reading
File. read (buffer, 1024); // read the file content from the beginning to the buffer zone (if you want to read data from different places, you need to set the cursor function seek, seektobegin, seektoend ..)
File. Close ();
// Cfile write content to the file
Cfile file;
Char buffer [1024] = "add the string to be written to the file here! ";
If (! File. open ("C: // aaa.txt", cfile: Create | cfile: Write) return; // open the file AAA. open the file in the form of (create a file without this file) write
File. Write (buffer, strlen (buffer ));
File. Close ();
// Cstdiofile Class Example:
Cstdiofile file;
Cstring STR; // stdiofile can directly use the string type cstring.
If (! File. Open ("C: // aaa.txt", cfile: moderead) return; // open the file AAA in the form of reading
File. readstring (STR); // read the content of a row to the STR string. Note that the cursor of the file is automatically set to the start position of the next row. Therefore, if you want to read the next row, use file. readstring (STR );
File. Close ();
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/lzhw1985/archive/2008/07/24/2704223.aspx