I want my open of non-existent output file to fail. Only if the output file exists I want open succeed. How can I do this with ofstream constructor?
2 Answers
std::ofstream's constructor takes a std::ios_base::openmode that specifies how the file should be opened. By default this value is set to ios_base::out, which will create the file if it does not exist. You can provide your own mode though, and if you use std::ios_base::out | std::ios_base::in then no file will be created. That would make your code look like this:
std::ofstream fout("some_file.ext", std::ios_base::out | std::ios_base::in);
3 Comments
std::basic_filebuf::open() for the supported combinations of flags and what they do together.#include <iostream.h> which was the pre C++ standard way. It might work in a compiler like TurboC++ but not in any standard complaint compiler.You cannot change the constructor of std::ofstream.
What you can do, is define your own custom stream class. Your own stream can check whether the file exists, and fail if it does not. If the file exists, you can delegate the functionality to an ofstream contained as a data member.
Another approach that doesn't require a custom stream might be to change your code to not even attempt to construct the stream until you've first verified that the file exists.
std::filesystem::existsif you have access to c++17. Otherwise I would try to open the file for reading first. If that fails it doesn't exist.