File input, getting pointer position
Sep 25, 2012 at 1:43pm UTC
Hi, I'm writing a program where I have to manipulate the stream pointer in an input file. I just wrote an testing program, I wanted to test if I get the right pointer position in a file where I have written few strings in a single line.
The contents of the file are "hello world foo(int) a=b".
The code is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
using namespace std;
#include <fstream>
int main()
{
ifstream Infile;
char c;
Infile.open("Input.txt" );
if (Infile.is_open())
{
Infile.seekg(0, ios::beg);
while (!Infile.eof())
{
cout << Infile.tellg() << ' ' ;
Infile.get(c);
//cout << c;
}
}
return 0;
}
The output of the program is
0 2 4 6 8 10 12 14 16 18 20 22 24 26
However, should'nt it be
0 1 2 3 4 5 6 7 8 9 10 11 12 13 and so on....
Because I am reading one character at a time and from what I know, the get(char) function also reads whitespaces and endlines...
I don't understand why the position pointer is being incremented by two..!?
Any clues?
Sep 25, 2012 at 2:34pm UTC
It is a failure of the STL streams class: they don't tellg() and seekg() properly in text mode. You can fix it by opening the file in binary mode:
10 11
Infile.open("Input.txt" , ios::binary);
Of course, you now have to deal with the possibility of extraneous
'\r' s in the input.
Topic archived. No new replies allowed.