Search code examples
c++fileexceptionifstream

Reading a file throws an exception


Does anyone have any idea what am i doing wrong

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;
}

When compiling I get

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) {
     ^

And when I run the code, the Exception occured when reading a file and the readErr.what() basic_ios::clear print.

I looked up a lot of examples and i can't see where i went wrong. Also, I'm on Ubuntu 14.04 if it helps.


Solution

  • I printed argv[0] and saw that IDE actually runs the program in a different directory. Sorry for my negligence