Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

c++ - Fstream's tellg / seekg returning higher value than expected

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 " " -- but when you read it in, that's converted to just a " ". When you use getline to read one line at a time, the s 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...