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

时间:2012-08-17 18:59:47

标签: c++ gcc fstream

我已经获得了使用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();

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

1 个答案:

答案 0 :(得分:1)

适合我。

.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

}