gpt4 book ai didi

c++ - tellg() 失败的可能原因?

转载 作者:行者123 更新时间:2023-11-28 08:31:02 27 4
gpt4 key购买 nike

ifstream::tellg() 为某个文件返回 -13。

基本上,我编写了一个分析一些源代码的实用程序;我按字母顺序打开所有文件,我从“Apple.cpp”开始,它工作得很好..但是当它到达“Conversion.cpp”时,总是在同一个文件上,在成功读取一行后 tellg() 返回 -13.

有问题的代码是:

for (int i = 0; i < files.size(); ++i) { /* For each .cpp and .h file */
TextIFile f(files[i]);
while (!f.AtEof()) // When it gets to conversion.cpp (not on the others)
// first is always successful, second always fails
lines.push_back(f.ReadLine());

AtEof 的代码是:

    bool AtEof() {
if (mFile.tellg() < 0)
FATAL(format("DEBUG - tellg(): %d") % mFile.tellg());
if (mFile.tellg() >= GetSize())
return true;

return false;
}

成功读取 Conversion.cpp 的第一行后,它总是崩溃并返回 DEBUG - tellg(): -13

这是整个TextIFile类(我写的,可能有错误):

class TextIFile
{
public:
TextIFile(const string& path) : mPath(path), mSize(0) {
mFile.open(path.c_str(), std::ios::in);

if (!mFile.is_open())
FATAL(format("Cannot open %s: %s") % path.c_str() % strerror(errno));
}

string GetPath() const { return mPath; }
size_t GetSize() { if (mSize) return mSize; const size_t current_position = mFile.tellg(); mFile.seekg(0, std::ios::end); mSize = mFile.tellg(); mFile.seekg(current_position); return mSize; }

bool AtEof() {
if (mFile.tellg() < 0)
FATAL(format("DEBUG - tellg(): %d") % mFile.tellg());
if (mFile.tellg() >= GetSize())
return true;

return false;
}

string ReadLine() {
string ret;
getline(mFile, ret);
CheckErrors();
return ret;
}

string ReadWhole() {
string ret((std::istreambuf_iterator<char>(mFile)), std::istreambuf_iterator<char>());
CheckErrors();
return ret;
}

private:
void CheckErrors() {
if (!mFile.good())
FATAL(format("An error has occured while performing an I/O operation on %s") % mPath);
}

const string mPath;
ifstream mFile;
size_t mSize;
};

平台是 Visual Studio,32 位,Windows。

编辑:适用于 Linux。

编辑:我找到了原因:行结尾。 Conversion 和 Guid 以及其他人都有\n 而不是\r\n。我用\r\n 保存了它们并且它有效。不过,这不应该发生,是吗?

最佳答案

如果不确切知道 Conversion.cpp 中的内容,很难进行猜测。 .但是,使用 < stream positions 没有被标准定义。您可能需要考虑在格式化之前显式转换为正确的整数类型;我不知道什么格式 FATALformat()期望执行或如何执行 %运算符重载。流位置不必以可预测的方式映射到整数,如果文件不是以二进制模式打开的话当然不是。

您可能需要考虑 AtEof() 的替代实现方式.像这样说:

bool AtEof()
{
return mFile.peek() == ifstream::traits_type::eof();
}

关于c++ - tellg() 失败的可能原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2121172/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com