读取文件会引发异常

时间:2014-10-23 09:36:09

标签: c++ file exception ifstream

有谁知道我做错了什么

inputFileName = argv[1];
outputFileName = argv[2];

std::ifstream readFile;
readFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
//set the flags for stream bits that indicate failure if ON
std::ofstream writeFile;
writeFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);

try{
    readFile.open(inputFileName);
    writeFile.open(outputFileName);

    //do some stuff

    readFile.close();
    writeFile.close();
}
catch(std::ifstream::failure &readErr) {
    std::cerr << "\n\nException occured when reading a file\n"
         << readErr.what()
         << std::endl;
    return -1;
}
catch(std::ofstream::failure &writeErr) {
    std::cerr << "\n\nException occured when writing to a file\n"
         << writeErr.what()
         << std::endl;
    return -1;
}

编译时我得到了

warning: exception of type 'std::ios_base::failure' will be caught [enabled by default]
     catch(std::ofstream::failure &writeErr) {
     ^
warning:    by earlier handler for 'std::ios_base::failure' [enabled by default]
     catch(std::ifstream::failure &readErr) {
     ^

当我运行代码时,Exception occured when reading a file和readErr.what()basic_ios::clear打印。

我查了很多例子,我不知道我哪里出错了。另外,如果它有帮助,我会使用Ubuntu 14.04。

2 个答案:

答案 0 :(得分:1)

inputFileName 是否存在?只需写下:

  catch ( std::exception const& e ) {
     std::cerr << "Exception: " << e.what() << std::endl;
   }

答案 1 :(得分:1)

我打印argv[0]并看到IDE实际上在不同的目录中运行程序。对不起我的疏忽