0

I am trying to backup a line in an ifstream. file.tellg() is returning a value I was not expecting. In the example bellow, after reading the first line (a string length of 15 characters) I expected file.tellg() to return 16. Instead, it is returning 41. Could someone please provide some insights on this behavior?

test.cpp

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

int main(){
    ifstream file("sample.ics", ios::in);

    string line;
    string key0;
    string key1;
    string value0;
    string value1;

    getline(file, line, '\n');

    cout << "line = " << line << endl;
    cout << "line.length = " << line.length() << endl; // should be 15;

    cout << "Attempt:" << endl;
    int pos = file.tellg(); // should be 16;
    cout << "  pos = " << pos << endl;

    getline(file, key0, ':');
    getline(file, value0, '\n');

    cout << "  First:" << endl;
    cout << "    " << key0 << ":" << value0 << endl;

    cout << "  backing up..." << endl;
    file.seekg(pos, ios_base::beg);

    getline(file, key1, ':');
    getline(file, value1, '\n');

    cout << "  Second:" << endl;
    cout << "    " << key1 << ":" << value1 << endl;

    file.close();
}

Output:

line = BEGIN:VCALENDAR
line.length = 15
Attempt:
  pos = 41
  First:
    CALSCALE:GREGORIAN
  backing up...
  Second:
    ION:2.0

sample.ics

BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:PUBLISH
...
ChrisMcJava
  • 2,145
  • 5
  • 25
  • 33
  • 1
    `std::istream::tellg()` doesn't return an `int` but an `std::streampos`: did you try using this type to restore the location? – Dietmar Kühl Feb 28 '15 at 19:48
  • I tried the code above. On my PC it's `pos = 16` – Andrey Derevyanko Feb 28 '15 at 19:52
  • Could be a line - ending compatibility problem. See [this](http://stackoverflow.com/questions/3682152/problem-with-istreamtellg), [this](http://www.cplusplus.com/forum/general/67355/) and [this](http://stackoverflow.com/questions/27234202/why-fstreamtellg-return-value-is-enlarged-by-the-number-of-newlines-in-the-i). – Anmol Singh Jaggi Mar 01 '15 at 01:08
  • streampos is still 41. and the same result happens – ChrisMcJava Mar 01 '15 at 13:13

1 Answers1

2

Try opening the file in binary mode and see if you get the same results:

ifstream file("sample.ics", ios::binary);

user4644
  • 228
  • 2
  • 5