I've got a fstream my_file("test.txt"), but I don't know if test.txt exists. In case it exists, I would like to know if I can read it, too. How to do that?
I use Linux.
Summary. Use the fopen() function to check if a file exists by attempting to read from it. Use the stat() function to check if a file exists by attempting to read properties from the file. Use the access() function with the F_OK flag to check if a file exists.
Check to make sure the file was successfully opened by checking to see if the variable == NULL. If it does, an error has occured. Use the fprintf or fscanf functions to write/read from the file. Usually these function calls are placed in a loop.
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True .
If the file exists, its contents are cleared unless it is a logical file. ab. Open a binary file in append mode for writing at the end of the file. The fopen function creates the file if it does not exist.
I would probably go with:
ifstream my_file("test.txt"); if (my_file.good()) { // read away }
The good
method checks if the stream is ready to be read from.
You might use Boost.Filesystem. It has a boost::filesystem::exist
function.
I don't know how about checking read access rights. You could look in Boost.Filesystem too. However likely there will be no other (portable) way than try to actually read the file.
EDIT (2021-08-26): C++17 introduced <filesystem>
and there you have std::filesystem::exists
. Boost is no longer needed for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With