tellg()失败的可能原因是什么?

时间:2010-01-22 23:04:44

标签: c++ file fstream ifstream line-endings

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

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

有问题的代码是:

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。

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

1 个答案:

答案 0 :(得分:1)

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

您可能想要考虑AtEof()的替代实现。说出类似的话:

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