将”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;
}
本文介绍了如何使用C++将字符串'hello'写入F:/test.txt的第1行,并详细展示了如何逐行读取并输出同一文件的内容。
4037

被折叠的 条评论
为什么被折叠?



