ifstream.read 在现有文件上失败,如果上一个打开失败

ifstream.read fails on an existing file if a previous open fails

本文关键字:失败 如果 上一个 read 文件 ifstream      更新时间:2023-10-16

在我的代码中,ifstream 对象尝试打开一个不存在的文件,但失败,然后打开一个成功的现有文件。但是,后续读取失败。

如果打开现有文件时没有先前失败,则读取成功。

打开失败后我缺少哪些清理?

以下代码

#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
    char *buf = new char[10];
    std::ifstream ifstr;
    ifstr.open("ExistingFile.txt", std::ios_base::in | std::ios_base::binary);
    std::cout << ifstr.is_open() << std::endl;
    ifstr.read(buf, 4);
    std::cout << ifstr.fail() << std::endl;
    ifstr.close();
    ifstr.open("NonExistingFile.txt", std::ios_base::in | std::ios_base::binary);
    std::cout << ifstr.is_open() << std::endl;
    ifstr.read(buf, 4);
    std::cout << ifstr.fail() << std::endl;
    ifstr.close();
    ifstr.open("ExistingFile.txt", std::ios_base::in | std::ios_base::binary);
    std::cout << ifstr.is_open() << std::endl;
    ifstr.read(buf, 4);
    std::cout << ifstr.fail() << std::endl;
    ifstr.close();
    return 0;
}

生产

1
0
0
1
1
1

你应该清除 ( ifstr.clear() ) 以前的错误

如果在关闭 if 之前清除流,ifstr.close() 可能会设置 ifstr fail 标志。如果 is_open() 失败,请不要关闭流

您可能需要

ifstr.close();后添加ifstr.clear();以清除故障位。