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

Jerry picture Jerry · Sep 5, 2009 · Viewed 84.4k times · Source

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.

Answer

Kim Gräsman picture Kim Gräsman · Sep 5, 2009

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.