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


Question

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.

1
62
10/5/2012 5:27:17 AM

Accepted Answer

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.

82
8/28/2013 8:54:46 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon