Questions and codes:
#include <iostream> #include <fstream>using namespace Std;int main () { fstream outfile,infile; Defines the file stream object outfile.open ("Data.dat", ios::out); Open file as output data,dat outfile<< "1111111111" <<endl; Save string to disk File data.dat outfile<< "aaaaaaaaaa" <<endl; outfile<< "AAAAAAAAAA" <<endl; outfile<< "**********" <<endl; Outfile.close (); Close Disk File Data.dat infile.open ("Data.dat", ios::in); Open file as input data,dat char line[80]; int i=0; while (!infile.eof ()) //successfully opening the file { i++; Infile.getline (line,sizeof (line)); Get data for each row cout<<i<< ":" <<line<<endl; } Infile.close (); Close Disk File Data.dat return 0;}
Operation Result:
After execution, a Data.dat file is generated in the program folder
Open the file in Notepad to see the result is the input result
Run the results, see the output of a total of five elements, and in the Data.dat file only four lines, that is because the last line of the Data.dat file has a carriage return character
Summary of Knowledge points:
When using the file stream, the first header file #include <fstream>
Then define an object
Ios::in open file in input mode
Ios::out Open the file as output, and if it already has a file of that name, delete its original content
Infile.getline (line,sizeof (line)); Get the data for each row
14th Week Reader Program 1: File stream