Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a file opened successfully with ifstream

Tags:

c++

io

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:

I am new to C++, as I am coming from C. So not sure I understand this error:

cannot call member function ‘bool std::basic_ios<_CharT, _Traits>::fail() const [with _CharT = char, _Traits = std::char_traits]’ without object

Code:

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; } 
like image 680
ant2009 Avatar asked Jun 06 '11 16:06

ant2009


People also ask

Does ifstream open file?

std::ifstream::open. Opens the file identified by argument filename , associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode. If the stream is already associated with a file (i.e., it is already open), calling this function fails.

What does Is_open () do in C++?

std::ifstream::is_openReturns whether the stream is currently associated to a file. Streams can be associated to files by a successful call to member open or directly on construction, and disassociated by calling close or on destruction.

Does ifstream automatically close?

Note that any open file is automatically closed when the ifstream object is destroyed.

Why is ifstream not Opening file C++?

The issue is most likely one of the following: 1) map_2. txt does not exist in the location you specified in your ifstream declaration. 2) You do not have sufficient rights to access the root folder of your C drive.


1 Answers

You can simply do this:

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() 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?

like image 68
Sven Avatar answered Oct 03 '22 21:10

Sven