开发者

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

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>开发者_JS百科(in_file), 
istreambuf_iterator<char>());


ifstream in_file(in_file_name.c_str());
if( in_file.fail() ) {
    cerr << "Error!" << endl;
}


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


you can use is_open method

cin >>  in_file_name ;

ifstream in_file(in_file_name.c_str());
if(!in_file.is_open())
{
   cout<<"Can't open the file";
}


Use operator! to test whether file open was succesful. Example:

std::ifstream fs(...);
if (!fs) {
    std::cerr << "Could not open file.\n";
}


All standard iostreams support a conversion to void*, which allows for testing. This means that you can do if(!in_file) { ... }.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜