检查文件是否已成功使用ifstream打开

编程入门 行业动态 更新时间:2024-10-28 15:33:17
本文介绍了检查文件是否已成功使用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 :: fail()const [with _CharT = char,_Traits = std :: char_traits]'without object

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.fail()替换!input_stream 我的代码在上面。

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打开

本文发布于:2023-10-11 17:35:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   ifstream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!