Problem in using seekg() to read file in C++

569 Views Asked by At

I am learning to read and write file in C++ and find a problem.

My test.txt file contains 3 string in 3 lines:

abc
def
mnp

My problem is: I don't understand why I need to use f.seekg(2, ios::cur); instead of f.seekg(1, ios::cur); I know how to use seekg() in c++ and I think that I just need to ignore 1 byte to get the next line by the getline() function.

This is my code:

ifstream f;
    f.open("D:\\test.txt", ios::in);
    string str1, str2, str3;
    f >> str1;
    f.seekg(2, ios::cur);
    getline(f, str2);
    getline(f, str3);
    cout << str1 << " " << str2 << " " << str3 << endl;
1

There are 1 best solutions below

1
hyde On

Reason for your trouble is explained for example here:
Why does std::getline() skip input after a formatted extraction?

However about your actual question about seekg. You open the file in text mode. This means that when you read the file, line feeds are given to your C++ code as single characters, '\n'. But on the disk they may be something else, and it seems you are running your code on Windows. There newline in a text file is typically two bytes, CR (ASCII code 13) and LF (ASCII code 10). Reading or writing in text mode will perform this conversion between a single character in your C++ string vs two bytes in the file for you.

seekg works on offsets and does not care about this, offsets are same whether you open the file in text or binary mode. If you use seekg to skip new line, your code becomes platform-dependent, on Windows you need to skip 2 bytes as explained above, while in other platforms such as Unix you need to skip just single byte.

So, do not use seekg for this purpose, see the linked question for better solutions.