c++ - 从失败的读取中恢复 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;
}
解决方案
推荐阅读
- python - 在 python 中使用 rpy2 运行用户定义的函数时出现 RRuntimeError
- c# - 椭圆变成长方形
- linux - 稍后在分配变量后使用变量引用扩展字符串
- node.js - 无法在 angular4 中使用数组到树的 npm 模块
- mysql - MySQL Workbench 查询返回 1 行,但 Jdbc 中的相同查询返回 0
- c# - 执行在数据集的 .xsd 中配置的存储过程
- google-api - cse 热门查询与谷歌搜索结果中的显示不完全相同
- python - 外部终端和VSCode之间的Python3不同
- c# - 下拉菜单在 View MVC 上不显示数据
- android - 如果 Glide 无法连接到远程服务器,Android 片段会从 drawable 中加载默认图像