ifstream.read 在现有文件上失败,如果上一个打开失败
ifstream.read fails on an existing file if a previous open fails
在我的代码中,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();
以清除故障位。
相关文章:
- 如果没有malloc,链表实现将失败
- 如果我重新定义 sqrt 函数,为什么使用 std::sqrt 失败?
- join() 失败,如果在线程内部调用 io_context.run()
- 如果原型是本地的,则使用流 I/O C++类型约束将失败
- 如果所有部分都失败,Catch2 将再次运行测试
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 如果出现警告,如何立即使自动测试失败
- 避免"如果清理失败"重复的模式
- 如果我在下面的代码中使用 list 而不是 vector,为什么在我尝试在迭代器之间执行减法的行中编译失败?
- SFINAE - 如果更复杂的功能失败,则回退到默认功能
- 如果一个人失败,如何防止多个CIN语句失败
- 如果容器不是调用函数中的引用,则使用 std::thread 传递对迭代器的引用将失败
- 如果应用程序从安装选项启动,则加载库失败,错误代码为 126
- C/C++ 套接字:如果我在 IPv6 TCP 连接之前执行任何操作,则连接将失败
- 如果 QApplication 执行延迟,QWebEngineView 在加载内容时会以静默方式失败
- 如果类没有默认可见性,静态断言如何失败
- 如果将键定义为std :: string,则存储在REDIS中的POD结构的验证将失败
- AC_CHECK_HEADER失败如果标题安装路径中有API
- Visual Studio 2010 CxxTest:如果测试失败,则生成失败
- 谷歌测试:如果测试失败,则执行其他操作