recoba78
recoba78

Reputation: 99

why the function tellg() does not return the good result?

I don't understand why my function tellg() jumps from 0 to 2 here is my code:

ifstream uploadFile("upload.txt");
 char letter;
    uploadFile.seekg(0);
    cout<<uploadFile.tellg()<<endl;
    while(uploadFile.get(letter))
        cout<<uploadFile.tellg()<<endl;
    return 0;

My file contains this line:

0 TS1

These are the results I expect:

0
1
2
3
4
5
6

but I get this:

0
2
3
4
5
6
7

Upvotes: 1

Views: 164

Answers (1)

rustyx
rustyx

Reputation: 85341

Your file upload.txt probably starts with a blank line:


0 TS1

ifstream in text mode (the default) treats newlines as a single character. But on Windows a newline consists of two bytes (CRLF, or \r\n). So each time a newline is read, the file position is advanced by 2.

You can open a file in binary mode:

ifstream uploadFile("in.txt", ios::binary);

Then get() will always read 1 byte at a time, so also \r and \n characters separately.

Upvotes: 2

Related Questions