Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file exists and is readable in C++?

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.

like image 327
Jerry Avatar asked Sep 05 '09 15:09

Jerry


People also ask

How do I make sure a file exists in C?

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.

How do you check if a file can be opened in C without opening it?

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.

How do you check and see if a file exists?

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 .

What happens if you open a file that doesn't exist in C?

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.


2 Answers

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.

like image 106
Kim Gräsman Avatar answered Oct 06 '22 10:10

Kim Gräsman


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.

like image 26
Adam Badura Avatar answered Oct 06 '22 12:10

Adam Badura