0

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?

12
  • You can make streams throw on failure, but as far as I know it can't be done for their constructors since it requires an instance to enable the behavior. Commented Feb 20, 2019 at 16:41
  • You can use std::filesystem::exists if you have access to c++17. Otherwise I would try to open the file for reading first. If that fails it doesn't exist. Commented Feb 20, 2019 at 16:42
  • Why was the question downvoted? It is a valid question, even though there is no good answer. Commented Feb 20, 2019 at 16:43
  • @super existing and being readable are very different things. Commented Feb 20, 2019 at 16:43
  • @FrançoisAndrieux and even when you do enable exceptions, they are super inconvenient to use. I am afraid, we have to admit that bad exception specification is one (of the several) shortcomings of standard streams. Commented Feb 20, 2019 at 16:44

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

See std::basic_filebuf::open() for the supported combinations of flags and what they do together.
Did ios::nocreate exist in some version of c++ as described here courses.cs.washington.edu/courses/cse373/99au/assignments/…
@RanjitKumar No, that never made it into the C++98 standard. If you look at the headers in the linked to post you'll see they are doing #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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.