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になっています
このずれはなぜ発生するのでしょうか?
よろしくお願いします