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

编辑:我发现病因:行结尾。转化率和GUID和别人有\ n代替\ r \ n。我用\ r \ n救了他们,而不是和它的工作。不过,这是不应该发生的是什么呢?

有帮助吗?

解决方案

这是很难不知道到底是什么在Conversion.cpp猜测。然而,使用与流位置<不是由标准限定。你可能想格式化之前需要考虑的一个显式转换为正确的整数类型;我不知道是什么格式FATALformat()预计执行或%运营商是如何超载。流位置没有在可预测,方式整数映射,肯定不是,如果文件没有以二进制模式打开。

您可能要考虑AtEof()的另一种实现。这样说:

bool AtEof()
{
    return mFile.peek() == ifstream::traits_type::eof();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top