保证在运行目录中存在text.txt文件,否则需要附加相对路径或绝对路径找到该文件。
测试代码如下:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream myfile;
//(1) 二选一: Append the text at the end.
myfile.open ("text.txt",ofstream::app);
myfile << "Writing this to a file.\n";
myfile << "Hi Tekken.\n";
myfile.close();
//(2) 二选一: Clean the text
myfile.open ("text.txt",ofstream::out);
myfile << "Writing this to a file.\n";
myfile << "Hi Tekken.\n";
myfile.close();
// 读取文件
string line;
myfile.open("text.txt");
if (myfile.is_open())
{
while(getline (myfile,line))
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file\n";
return 0;
}
运行结果:
tekken@tekken:~/C++WS$ ./a.out
Writing this to a file.
Hi Tekken.
网友评论