Coder Perfect

In C++, how do you check if a file exists and is readable?


I have a my file(“test.txt”) fstream, but I’m not sure if test.txt exists. If it does exist, I’d like to know if I can read it as well. What is the best way to accomplish this?

I use Linux.

Asked by Jerry

Solution #1

I’d most likely choose:

ifstream my_file("test.txt");
if (my_file.good())
  // read away

The excellent method determines whether or not the stream is ready to read from.

Answered by Kim Gräsman

Solution #2

You might make advantage of Boost.Filesystem. A boost::filesystem::exist method is included.

I’m not sure how to check for read access rights. You might also take a look at Boost.Filesystem. However, there will most likely be no other (portable) option except to attempt to read the file.

EDIT (2021-08-26): C++17 added the filesystem> keyword, resulting in std::filesystem::exists. This no longer necessitates the use of Boost.

Answered by Adam Badura

Solution #3

If you’re on Unix, you can use access() to see if it’s readable. If ACLs are in use, things get a little more complicated; in this situation, it’s best to just open the file using ifstream and attempt reading; if you can’t, the ACL may be preventing you from doing so.

Answered by neoneye

Solution #4

What Operating System/platform?

You can use fstat on Linux/Unix/MacOSX.

GetFileAttributes can be used on Windows.

With normal C/C++ IO routines, there is usually no portable way to do this.

Answered by Pablo Santa Cruz

Solution #5

Cross-platform C++17: std:: is used to verify the existence of a file. readability with std::filesystem::status & std::filesystem::perms and filesystem::exists:

#include <iostream>
#include <filesystem> // C++17
namespace fs = std::filesystem;

/*! \return True if owner, group and others have read permission,
            i.e. at least 0444.
bool IsReadable(const fs::path& p)
    std::error_code ec; // For noexcept overload usage.
    auto perms = fs::status(p, ec).permissions();
    if ((perms & fs::perms::owner_read) != fs::perms::none &&
        (perms & fs::perms::group_read) != fs::perms::none &&
        (perms & fs::perms::others_read) != fs::perms::none
        return true;
    return false;

int main()
    fs::path filePath("path/to/test.txt");
    std::error_code ec; // For noexcept overload usage.
    if (fs::exists(filePath, ec) && !ec)
        if (IsReadable(filePath))
            std::cout << filePath << " exists and is readable.";

Consider looking at the file type as well.

Answered by Roi Danton

Post is based on