Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c++ - Checking if a file opened successfully with 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...