C ++ reads and writes text files
# Include <iostream>
# Include <fstream>
Using namespace STD;
Int main ()
{
Const char filename [] = "mytext.txt ";
Ofstream o_file;
Ifstream I _file;
String out_text;
// Write
O_file.open (filename );
For (INT I = 1; I <= 10; I ++)
{
O_file <"no" <I <"line" N "; // write the content to a text file.
}
O_file.close ();
// Read
I _file.open (filename );
If (I _file.is_open ())
{
While (I _file.good ())
{
I _file> out_text; // store the read content in the out_text variable.
Cout <out_text <Endl; // output the read content on the console. Why does the last line appear twice?
}
}
Else
Cout <"Open File:" <FILENAME <"error! ";
I _file.close ();
System ("pause ");
Return 0;
}
######################################## ######################################
# Include "stdafx. H"
# Include <iostream>
# Include <fstream>
# Include <string>
Using namespace STD;
Int _ tmain (INT argc, _ tchar * argv [])
{
Const char filename [] = "test.doc ";
Ofstream o_file;/* output stream: output data from the memory. ofstream outputs data to the file, so it is "write "*/
Ifstream I _file;/* input data to the memory. ifstream indicates that the input data is in the file, so it is "read" for the file "*/
String out_text;
// Write
O_file.open (filename );
For (INT I = 0; I <= 12; I ++)
{
O_file <"th" <I <"N"; // write the content to the text
}
O_file.close ();
// Read
I _file.open (filename );
If (I _file.is_open ())
{
While (I _file> out_text)
{
Cout <out_text <Endl;
}
}
Else
Cout <"Open File:" <FILENAME <"error! ";
I _file.close ();
System ("pause ");
Return 0;
}