Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fstream's tellg / seekg returning higher value than expected

Tags:

c++

Why does this fail, it's supposed to be simple and work ?

fisier.seekg(0, ios::end);
long lungime = fisier.tellg();

This returns a larger value than that of the file resulting in a wrong

char *continut = new char[lungime];

Any idea what the problem could be ?

I also tried counting to the end of the file one char at a time, that rendered the same result, a higher number than expected. But upon using getline() to read one line at a time, it works, there are no extra spaces...

like image 983
Cosmin Avatar asked Dec 17 '22 01:12

Cosmin


2 Answers

At a guess, you're opening the file in translated mode, probably under Windows. When you simply seek to the end of the file, the current position doesn't take the line-end translations into account. The end of a line (in the external file) is marked with the pair "\r\n" -- but when you read it in, that's converted to just a "\n". When you use getline to read one line at a time, the \ns all get discarded as well, so even on a system (e.g. Unix/Linux) that does no translation from external to internal representation, you can still expect those to give different sizes.

Then again, you should really forget that new [] exists at all. If you want to read an entire file into a string, try something like this:

std::stringstream continut;
continut << fisier.rdbuf();

continut.str() is then an std::string containing the data from the file.

like image 72
Jerry Coffin Avatar answered Dec 24 '22 01:12

Jerry Coffin


Jerry Coffin is right about the line endings.

However, you don't have to use stringstream to read the entire file correctly. You just have to open it as binary by using std::ios::binary in std::ifstream constructor.

like image 25
dotsquid Avatar answered Dec 24 '22 02:12

dotsquid