Catch Segmentation fault in c++

前端 未结 6 1193
半阙折子戏
半阙折子戏 2020-12-09 16:42

Does a try-catch block catch segmentation fault errors?

I am reading a text file using the function given below but sometimes the file is empty and the

6条回答
  •  误落风尘
    2020-12-09 17:23

    You can try to add a little test to see if ifs is valid:

    #include 
    #include 
    
    int main(int argc, char * argv[]){
       std::ifstream ifs( "notExists" );
       if( ifs.is_open()) {
          char line[1024];
          while(! ifs.fail() && ifs.getline( line, sizeof( line ))) {
            std::cout << line << std::endl;
          }
       }
       else {
          std::cout << "file doesn't exists." << std::endl;
       }
       std::cout << "done." << std::endl;
        return 0;
    }
    

    This program runs and output:

    file doesn't exists.
    done.
    

    bool std::ifstream::is_open();

    See the getline global function for more information, if it fail, it set some bit not checked here.

    Errors are signaled by modifying the internal state flags:

    • eofbit: The end of the source of characters is reached during its operations.
    • failbit: No characters were extracted because the end was prematurely found.Notice that some eofbit cases will also set failbit.
    • badbit: An error other than the above happened.

    Additionally, in any of these cases, if the appropriate flag has been set with is's member function ios::exceptions, an exception of type ios_base::failure is thrown.

提交回复
热议问题