eaglesky
eaglesky

Reputation: 720

Why seekg function doesn't work?

Here's the code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
  string infile(argv[1]);
  ifstream fin(infile.data());

  string var_name;
  char ch = fin.get();
  cout << ch << endl;

  ch = fin.get();
  cout << ch << endl;

  ch = fin.get();
  cout << ch << endl;

  cout << "pos: " << fin.tellg() << endl;
  fin.seekg(-sizeof(char),ios::cur);
  cout << "pos: " << fin.tellg() << endl;

  ch = fin.get();
  cout << ch << endl;

  return 0;
}

the file content is just a string:

<
?
x
m

and the output is:

<\n
?\n
x\n
pos: 3\n
pos: 2
x

Why the last character printed is still 'x' ?? Why doesn't seekg function move the file pointer back for one byte?

Upvotes: 0

Views: 2612

Answers (2)

Aniket Inge
Aniket Inge

Reputation: 25725

It will work if you do this: fin.seekg(-sizeof(char)-1,ios::cur);

Note: seeking to an arbitrary location in a text file is Undefined Behavior. See here: How to read the 6th character from the end of the file - ifstream?

Upvotes: 2

Michael Madsen
Michael Madsen

Reputation: 55009

The position of the file pointer was 3 after reading the x, but the x itself is located at position 2 (since the very first character is at position 0). Moving back by 1 character will put the file pointer at the character it most recently read, which is exactly what's happening here.

If you want to move to the character immediately before the last character read, you need to seek by -2, not -1.

Upvotes: 4

Related Questions