參考鏈接:
1、https://www.w3cschool.cn/cpp/cpp-files-streams.html
2、https://blog.csdn.net/jllongbell/article/details/79087281
3、https://blog.csdn.net/buknow/article/details/87973205
4、https://www.cnblogs.com/nkzhangcheng/p/7722568.html
#include <iostream>
#include <fstream>
#include <cassert>// assert()
using namespace std;
void testWrite()
{
// write file
ofstream outfile;
outfile.open("afile.dat", ios::out | ios::trunc);
assert(outfile.is_open());
for(int i = 0;i < 10;i++) outfile << "Hello file world!" << endl;
outfile.close();
// read file
ifstream infile;
string buffstr;
infile.open("afile.dat", ios::in);
assert(infile.is_open());
// read line and line
while(getline(infile, buffstr))
{
cout << buffstr << endl;// red line string
break;
}
// read char and char
infile.seekg(16, ios::beg);// set to file begin
char ch = '\0';
infile >> noskipws;// not ignore Spaces and enter
while(!infile.eof())
{
infile >> ch;
cout << ch << ",";
}
infile.close();
}
int main(int argc, char *argv[])
{
cout << "Hello main World!" << endl;
testWrite();
return 0;
}