C++ 没有使用 fstream 将输出发送到文件

C++ No output sent to file using fstream

本文关键字:出发 输出 文件 fstream C++      更新时间:2023-10-16

我有这段代码,它使用 fstream 来读取和写入文件。fstream 对象被保存为对象的成员,并在构造函数中初始化,如下所示:

idmap.open(path, std::fstream::in | std::fstream::out | std::fstream::app);

如果文件尚不存在,则会正确创建该文件。然后它被写成这样:

idmap.seekp(0, std::fstream::end);
idmap << str.size() << ':' << str << 'n';
idmap.flush();
idmap.sync();

应该这样阅读,但我不知道它是否有效,因为该文件一直是空的:

idmap.seekg(0);
while (!idmap.eof()) {
    idmap.getline(line, 1024);
    idtype id = getIDMapEntry(std::string(line));
    if (identifier.compare(nfile.getIdentifier()) == 0) {
        return nfile;
    }
}

然后在程序退出时关闭:

idmap.close();

这可能是程序中的其他内容,但我想我会在这里问,以防我做了一些愚蠢的事情,并并行挖掘其他所有内容。

对我有用。

.eof()错误外,该程序完全按预期工作:

#include <fstream>
#include <iostream>
int main() {
  std::fstream idmap;
  const char path[] = "/tmp/foo.txt";
  idmap.open(path, std::fstream::in | std::fstream::out | std::fstream::app);
  std::string str("She's no fun, she fell right over.");
  idmap.seekp(0, std::fstream::end);
  idmap << str.size() << ':' << str << 'n';
  idmap.flush();
  idmap.sync();
  idmap.seekg(0);
#if 1
  // As the user presented, with .eof() bug
  char line[1024];
  while (!idmap.eof())
  {
    idmap.getline(line, 1024);
    std::cout << line << "n";
  }
#else
  // With fix for presumably unrelated .eof() bug
  std::string line;
  while(std::getline(idmap, line)) {
    std::cout << line << "n";
  }
#endif
}