Fstream的tellg / seekg返回比预期更高的值 [英] Fstream's tellg / seekg returning higher value than expected
问题描述
为什么失败,它应该是简单和工作?
fisier.seekg(0,ios :: end);
long lungime = fisier.tellg();
这会返回比文件大的值,导致错误
char * continut = new char [lungime];任何想法可能是什么问题? p>我也试图计数到文件结束一个字符,一次,提供了相同的结果,比预期更高的数字。但是在使用getline()一次读取一行时,它工作,没有额外的空格... 解决方案在猜测,你打开文件的翻译模式,可能在Windows下。当你只是寻找到文件的结尾,当前位置不考虑行末翻译。一行的结束(在外部文件中)用\r\\\
对标记 - 但是当你读它时,它被转换为一个\\\
。当您使用 getline
一次读取一行时, \\\
的所有内容也会被丢弃,因此即使在没有从外部到内部表示的翻译的系统(例如Unix / Linux)上,你仍然可以期望那些具有不同的大小。
真的忘记了 new []
存在。如果要将整个文件读入字符串,请尝试这样的:
std :: stringstream continut;
continut<< fisier.rdbuf();
std :: string
包含来自文件的数据。
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...
解决方案 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 \n
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.
这篇关于Fstream的tellg / seekg返回比预期更高的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!