c++ - 在 C++ 中使用 fstream 创建和读取/写入文件

标签 c++ fstream

我想创建一个文件,然后打开它并重写它。

我发现我可以通过简单地这样做来创建一个文件:

#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/

相关文章:

c++ - 将整个文件读入线 vector 的最有效方法

c++ - 为 RAII 模板类编写对象生成器的更好方法?

c++ - 在 C++ 中格式化列

C++:如何将十六进制字符转换为无符号字符?

c++ - ofstream 不会写入所有内容——截断的数据

c++ - fstream.read() 根本不读取任何内容

c++ - std::ofstream 不接受 << 运算符的 const char *

可以为 NULL 的 C++ 字符串

c++打开.txt文件并读取数字以放置在数组中

c++ - eof问题c++