1.从文件中读数据
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main(int argc, char**argv)
{
fstream myfile;
myfile.open("./test.txt", ifstream::in);
if (myfile.is_open())
{
//方法一:使用getline,一行一行地读
vector<string> vStr;
string buff;
while (getline(myfile, buff))
{
vStr.push_back(buff);
}
//注意:使用以下两种方法,遇到空格,会自动换行
//方法二:使用流
//string buff;
//vector<string> vStr;
//while (myfile >> buff)
//{
// vStr.push_back(buff);
//}
//方法三:使用istream_iterator迭代器
//vector<string> vStr;
//istream_iterator<string> in(myfile), end;
//while (in != end)
//{
// vStr.push_back(*in++);
//}
//方法三可以简写为:
//istream_iterator<string> in(myfile), end;
//vector<string> vStr(in, end);
//打印读取到的内容
for(auto i : vStr)
{
cout << i<< endl;
}
}
myfile.close();
system("pause");
}
2.向文件中写数据
#include <iostream>
#include <string>
#include <fstream> //文件流工具类头文件
using namespace std;
void test()
{
//1,包含头文件fstream
//2,创建文件流对象
ofstream ofs;
//3,打开文件流对象
ofs.open("textWXD.txt", ios::out);
//4,写数据 “<<”
ofs << "peggy" << endl;
//5,关闭文件流对像
ofs.close();
}
int main()
{
test();
}