• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ ofstream question

I am writing a C++ program in which I only wish to open a file if it doesn't exist - in other words, I am not allowed the program to overwrite a file. How can I specify this when opening the ofstream? Thanks.
 
set the ios::nocreate flag when you try to open it. Like this (open a file for output, only if it doesn't exist):

file.open("filename", ios:: out|ios::nocreate);

edit: Ok, I'm a bonehead ... that's the exact opposite of what you want to do ... it succeeds only if the file already exists.

So, you can do it in two steps.
Attempt to open it with the nocreate flag. If that succeeds, you know the file exists, so close it and move on. If it fails, it likely means that the file doesn't exist, attempt to open it without the nocreate flag.

There is probably an easier way!
 
Back
Top