Ifstream is misaligned

Asked 2 years ago, Updated 2 years ago, 29 views

Use tellg() and seekg() for ifstream to save the file loading location and
I tried to call that save location later
However, I am looking for the cause because the reading position is out of place.

Read File (text.txt)

helloworld

Source

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

void print(std::ifstream&ifs);

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

  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;
}

Expected Results

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"

Actual Results

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"

If you do ifs.get() when pos is 3, pos should be 4, but
Actually, I skipped one and the pos is 5.
Why does this shift occur?

Thank you for your cooperation

c++

2022-09-30 15:30

1 Answers

https://stackoverflow.com/a/27089585.How about cutting the buffer?

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

void print(std::ifstream&ifs);

int main() {
  // Change from here
  std::ifstream ifs;
  ifs.rdbuf()->pubsetbuf(nullptr,0);
  ifs.open("test.txt");
  // Change to this point
  std::streampospos;

  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;
}


2022-09-30 15:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.