We often integrate some command programs, such as cout <, CIN>. in actual projects, you will not need to use cout to output data on the screen. there are many operations to read and write files on the hard disk.
How can I read and write files without using MFC or win api.STL provides some classes for you to easily read and write files. There are three common classes:
Fstream: You can write or read files.
Ofstream: Only files can be written.
Ifstream: Only files can be read.
Write files
# Include <iostream>
# Include <string>
# Include <fstream> // remember to reference this header file
Using namespace STD;
Int main ()
{
// Use fstream to write files
String filepath = "d :\\ arwen.txt ";
Fstream writefile;
Writefile. Open (filepath, IOS: Out); // open the file. If the file does not exist, create the file.
Writefile <"Hello Arwen. "<Endl; // write content to the file. If the file is opened, the content will be overwritten. if you only want to add content to the original content, open the file like this
// Writefile. Open (filepath, IOS: Out | IOs: APP );
Fstream. Close ();
// Use ofstream to write files
String filepath = "d :\\ tmp.txt ";
Ofstream filewriteonly;
Filewriteonly. Open (filepath, IOS: Out );
Filewriteonly <"I am Temp File" <Endl;
Filewriteonly. Close ();
Read files
// Use fstream to read files
String filepath = "d :\\ arwen.txt ";
Fstream readfile;
Readfile. Open (filepath, IOS: In );
Char ch;
While (readfile. Get (CH ))
Cout <ch;
Readfile. Close ();
// Use ifstream to read files
String filepath = "d :\\ tmp.txt ";
Ofstream filereadonly;
Filereadonly. Open (filepath, IOS: In );
While (filereadonly. Get (CH ))
Cout <ch;
Filereadonly. Close ();
Return 0;
}
The above read file is a char read at a time, you can also read a row at a time.
For example
String filepath = "d :\\ tmp.txt ";
Ofstream filereadonly;
Filereadonly. Open (filepath, IOS: In );
Char mystring [100] = {'0 '};
While (filereadonly. Getline (mystring, 1000) // The second parameter is the buffer size.
Cout <mystring;