读取文件会引发异常

Reading a file throws an exception

本文关键字:异常 文件 读取      更新时间:2023-10-16

有人知道我做错了什么吗

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 << "nnException occured when reading a filen"
         << readErr.what()
         << std::endl;
    return -1;
}
catch(std::ofstream::failure &writeErr) {
    std::cerr << "nnException occured when writing to a filen"
         << 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上。

是否存在inputFileName?只需写:

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

我打印了argv[0],发现IDE实际上在不同的目录中运行程序。抱歉我的疏忽