0

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();

それはおそらくプログラムの他の何かですが、私が何かばかげたことをした場合に備えてここで質問し、他のすべてを並行して掘り下げます。

4

1 に答える 1

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

}
于 2012-08-17T20:42:52.687 に答える