1、创建dat/txt文件(若dat文件不存在时)并向其中写入数据

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream outfile("E:\\myfile.dat", ofstream::app);
//ofstream outfile("E:\\myfile.txt", ofstream::app);

string temp = "O \nM \nG \n!"; //写入内容
if(outfile.is_open())
{
outfile<<temp<<"\n";
outfile.close();
}
else
{
cout<<"can not open the file \n"<<endl;
return -1;
}
return 0;
}

2、读取dat/txt文件中的数据

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream infile("E:\\myfile.dat");
//ifstream infile("E:\\myfile.txt");

string temp;
if (!infile.is_open())
{
cout<<"can not open the file \n"<<endl;
return -1;
}
while(getline(infile,temp))
{
cout<<temp<<"\n";
}
infile.close();
return 0;
}