0

ifstreamに対しtellg()とseekg()を使って、ファイルの読み込み位置を保存し、
後でその保存位置を呼び出そうとしました
しかし、読み取り位置が想定とずれるためその原因を探しています

読み込みファイル(text.txt)

helloworld

ソース

#include <fstream>
#include <iostream>
#include <typeinfo>

void print(std::ifstream& ifs);

int main() {
  std::ifstream ifs("test.txt");
  std::streampos pos;

  print(ifs);
  print(ifs);
  pos = ifs.tellg();
  std::cout << "save the pos : " << pos << std::endl;
  print(ifs);
  print(ifs);
  print(ifs);
  ifs.seekg(pos);
  std::cout << "load the pos : " << pos << std::endl;
  print(ifs);
  print(ifs);
  print(ifs);

  return 0;
}

void print(std::ifstream& ifs) {
  char word = ifs.get();
  std::cout << ifs.tellg() << ": word \"" << word << "\"" << std::endl;
}

予想される結果

2: word "h"
3: word "e"
save the pos : 3
4: word "l"
5: word "l"
6: word "o"
load the pos : 3
4: word "l"
5: word "l"
6: word "o"

実際の結果

2: word "h"
3: word "e"
save the pos : 3
4: word "l"
5: word "l"
6: word "o"
load the pos : 3
5: word "l"
6: word "o"
7: word "w"

想定ではposが3の時にifs.get()を行うとposが4になるはずなのに、
実際には一つ飛ばしてposが5になっています
このずれはなぜ発生するのでしょうか?

よろしくお願いします

2
  • 1
    ウチでは想定通りの動作をします cygwin64 / vs2019 (提示の予想される結果は1ずれています)あなたの使ったコンパイラであるとか test.txt に BOM がついているとか、その辺を追記していただくと別の回答が付くかもしれません。
    – 774RR
    2020年4月19日 23:20
  • ご指摘ありがとうございます。 win10環境でmingw-w64(Msys2)を使ってコンパイルしました。 BOMはバイナリを確認した限りだと無いです。 >>ウチでは想定通りの動作をします。 もしや、と思ってubuntu 18.04 g++で試してみたところ、 774RRさんのおっしゃる通り、提示の結果と全体的に1ずつずれるものの 動作自体は想定通りになりました(書き方が難しい) コンパイラ周りの問題かもしれません。もう少し調べてみます。 コンパイラは盲点だったので非常に助かりました。ありがとうございます。
    – ncradle
    2020年4月20日 15:43

1 件の回答 1

0

https://stackoverflow.com/a/27089585 のように思えます。バッファを切るとどうでしょうか?

#include <fstream>
#include <iostream>
#include <typeinfo>

void print(std::ifstream& ifs);

int main() {
  // ここから変更
  std::ifstream ifs;
  ifs.rdbuf()->pubsetbuf(nullptr, 0);
  ifs.open("test.txt");
  // ここまで変更
  std::streampos pos;

  print(ifs);
  print(ifs);
  pos = ifs.tellg();
  std::cout << "save the pos : " << pos << std::endl;
  print(ifs);
  print(ifs);
  print(ifs);
  ifs.seekg(pos);
  std::cout << "load the pos : " << pos << std::endl;
  print(ifs);
  print(ifs);
  print(ifs);

  return 0;
}

void print(std::ifstream& ifs) {
  char word = ifs.get();
  std::cout << ifs.tellg() << ": word \"" << word << "\"" << std::endl;
}

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。