将”hello”写入F:/test.txt的第1行
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream outfile;
outfile.open("F:/test.txt",ios::out);
if(!outfile)
{
cout<<"file can not open"<<endl;
abort();
}
for(int i=0;i<1;i++)
{
outfile<<"hello\n";
}
outfile.close();
return 0;
}
将F:/test.txt每一行一次读取并输出
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream in("F:/test.txt");
string filename;
string line;
if (in) // 有该文件
{
while (getline(in, line)) // line中不包括每行的换行符
{
cout << line << endl;
}
}
else // 没有该文件
{
cout << "no such file" << endl;
}
return 0;
}