ifstream creates file if it doesn't exist

c++, linux, std

Solution

You can set the `failbit` in the exceptions flag for the `ifstream`:

std::ifstream log;
log.exceptions ( std::ifstream::failbit );
try {
    log.open ("test.txt");
}
catch (std::ifstream::failure e) {
    std::cout << "Exception opening/reading file\n";
}

Source

I've tested, and `ifstream` will throw a `failure` exception if the file cannot be opened, e.g. file not found, no read permissions. It will open read-only.

Problem

I'm having some trouble writing a Linux console app which reads apache logs. I need to handle bash script arguments, the last one being a path to the log file. My problem is that if the file doesn't exist, I would like to throw an exception. But when I try to open the file in read-only mode, instead of failing it creates the file ! Here's the code : ``` // logreader.h #include <string> #include <sstream> #include <iostream> #include <fstream> #include <stdexcept> class LogReader { public: LogReader(int, const char **); virtual ~LogReader(); // ... private: std::ifstream log_; }; // logreader.cpp #include <logreader.h> LogReader::LogReader(int argc, const char ** argv): log_() { log_.exceptions(std::ifstream::failbit | std::ifstream::badbit); for (int i = 1; i < argc; ++i) { std::string arg(argv[i]); if (i == argc - 1) { try { log_.open(arg.c_str(), std::ifstream::in); } catch (std::ifstream::failure) { throw std::runtime_error("The file " + arg + " wasn't opened"); } } } } LogReader::~LogReader() { } // main.cpp #include <logreader.h> int main(int argc, const char ** argv) { LogReader(argc, argv); return 0; } ``` Script call: ``` jmcomets $ ./test -g -l jmcomets $ ls -l -rw-rw-r-- 1 jmcomets jmcomets 0 Nov 14 22:41 -l ```

Original source