Checking if a file opened successfully with ifstream(使用 ifstream 检查文件是否成功打开)
问题描述
我有以下内容可以打开文件进行阅读.但是,我想检查以确保文件已成功打开,因此我使用失败来查看标志是否已设置.但是,我不断收到以下错误:
I have the following that will open a file for reading. However, I want to check to make sure that the file was open successfully, so I am using the fail to see if the flags have been set. However, I keep getting the following error:
我是 C++ 新手,因为我来自 C.所以不确定我是否理解这个错误:
I am new to C++, as I am coming from C. So not sure I understand this error:
不能调用成员函数‘bool std::basic_ios<_CharT,_Traits>::fail() const [with _CharT = char, _Traits = std::char_traits]' 无对象
cannot call member function ‘bool std::basic_ios<_CharT, _Traits>::fail() const [with _CharT = char, _Traits = std::char_traits]’ without object
代码:
int devices::open_file(std::string _file_name)
{
ifstream input_stream;
input_stream.open(_file_name.c_str(), ios::in);
if(ios::fail() == true) {
return -1;
}
file_name = _file_name;
return 0;
}
推荐答案
你可以简单地这样做:
int devices::open_file(std::string _file_name)
{
ifstream input_stream;
input_stream.open(_file_name.c_str(), ios::in);
if(!input_stream)
{
return -1;
}
file_name = _file_name;
return 0;
}
fail() 不是静态方法,你必须在一个实例上而不是一个类型上调用它,所以如果你想使用fail(),请将 !input_stream 替换为 input_stream.fail() 在我上面的代码中.
fail() is not a static method, you must call it on an instance not a type, so if you want to use fail(), replace !input_stream with input_stream.fail() in my code above.
我确实想知道你在这里想达到什么目的.您正在打开文件并立即再次关闭它.你只是想检查文件是否存在?
I do have to wonder what you're trying to achieve here. You're opening the file and immediately close it again. Are you simply trying to check if the file exists?
这篇关于使用 ifstream 检查文件是否成功打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ifstream 检查文件是否成功打开
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
