首页 > 解决方案 > 从失败的读取中恢复 ifstream

问题描述

我目前有一段代码使用 ifstream 从文件中读取文本。该文件的每一行对应于必须编码到结构中的不同数据。我的“encodeLine”函数负责这个。

为了安全起见,我希望我的系统能够处理太大而无法放入其变量的数据。例如,如果将数字 999999999 读入一个简短的,我希望程序能够继续读取其余的行。

目前,当我遇到这样的数据时,我会打印出“ERROR”并清除流。但是,当我执行更多读取时,读取的数据已损坏。例如,在下一行应该读取数字“1”,但读取的是 27021 之类的数字。

如何重置 ifstream 以继续进行有效读取?

这是我的代码:

ifstream inputStream;
inputStream.open(foo.txt);
char token[64];

int totalSize = 0;

// Priming read
inputStream >> token;

while(inputStream.good())
{
    // Read and encode line of data from file
    totalSize = totalSize + encodeLine(inputStream, &recordPtr, header, filetypeChar)

    if(!inputStream.eof() && !inputStream.good())
    {
         printf("ERROR");
         inputStream.clear();
    }
    else if(inputStream.eof())
    {
         break;
    }

    inputStream >> token;
}

标签: c++iostreamifstream

解决方案


推荐阅读