I am implementing file saving functionality within a Qt application using C++.
I am looking for a way to check to see if the selected file already exists before writing to it, so that I can prompt a warning to the user.
I am using an std::ofstream
and I am not looking for a Boost solution.
One of the way would be to do
stat()
and check onerrno
.A sample code would look look this:
This works irrespective of the stream. If you still prefer to check using
ofstream
just check usingis_open()
.Example:
Hope this helps. Thanks!
Note that in case of an existing file, this will open it in random-access mode. If you prefer, you can close it and reopen it in append mode or truncate mode.
This method is so far the shortest and most portable one. If the usage is not very sophisticated, this is one I would go for. If you also want to prompt a warning, I would do that in the main.
Try
::stat()
(declared in<sys/stat.h>
)With
std::filesystem::exists
of C++17:See also
std::error_code
.In case you want to check if the path you are writing to is actually a regular file, use
std::filesystem::is_regular_file
.This is one of my favorite tuck-away functions I keep on hand for multiple uses.
I find this much more tasteful than trying to open a file if you have no immediate intentions of using it for I/O.