Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an error message if a file can't be opened, C++

Tags:

c++

fstream

I'm using fstream to open up .txt files with C++. So far it's working great. However, I'd like my console to display an error message if the input_file can't be opened. How should I go about this?

Snippet:

cin >>  in_file_name ;

ifstream in_file(in_file_name.c_str());

in_file_str.assign(istreambuf_iterator<char>(in_file), 
istreambuf_iterator<char>());
like image 445
rectangletangle Avatar asked Nov 22 '25 04:11

rectangletangle


2 Answers

ifstream in_file(in_file_name.c_str());
if( in_file.fail() ) {
    cerr << "Error!" << endl;
}
like image 151
peoro Avatar answered Nov 23 '25 20:11

peoro


Use fail() to determine whether the ifstream was successfully opened or not.

like image 23
Oliver Charlesworth Avatar answered Nov 23 '25 21:11

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!