【问题标题】:Why fstream prints out last record of a file为什么 fstream 打印出文件的最后一条记录
【发布时间】:2019-03-25 12:07:27
【问题描述】:

为什么二进制文件的最后一条记录被打印了两次?

while( (inFile)
{
    inFile.read(reinterpret_cast <char*> (&acc), sizeof(acc));  
    display(acc);
}

【问题讨论】:

标签: c++ binary fstream


【解决方案1】:

因为您的代码应该读取

while (inFile.read(reinterpret_cast<char*>(&acc), sizeof(acc))
{
    display(acc);
}

您的版本仅在您打印失败的读取之后测试失败。或者换一种说法,while (infile) 不是测试下一次读取是否成功,而是测试最后一次读取是否成功。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-06
    • 2018-12-31
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多