我想创建一个文件,然后打开它并重写它。
我发现我可以通过简单地这样做来创建一个文件:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile ("test.txt");
outfile << "my text here!" << endl;
outfile.close();
return 0;
}
虽然这可以创建测试文件,但我无法打开文件然后对其进行编辑。即使在创建文件后,这个(下图)也不起作用。
outfile.open("test.txt", ios::out);
if (outfile.is_open())
{
outfile << "write this to the file";
}
else
cout << "File could not be opened";
outfile.close;
最佳答案
如果“不起作用”是指文本被覆盖而不是附加,则需要将 std::ios::app
指定为调用打开的标志之一让它附加更多数据而不是覆盖所有内容。
outfile.open("test.txt", ios::out | ios::app);
以下示例对我来说效果很好:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile ("test.txt");
outfile << "my text here!" << endl;
outfile.close();
outfile.open("test.txt", ios::out | ios::app );
if (outfile.is_open())
outfile << "write this to the file" << endl;
else
cout << "File could not be opened";
outfile.close();
return 0;
}
生成以下文本文件:
my text here!
write this to the file
关于c++ - 在 C++ 中使用 fstream 创建和读取/写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29781184/