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

前端 未结 8 1448
时光说笑
时光说笑 2020-12-13 12:19

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

相关标签:
8条回答
  • 2020-12-13 12:34

    I know the poster eventually said they were using Linux, but I'm kind of surprised that no one mentioned the PathFileExists() API call for Windows.

    You will need to include the Shlwapi.lib library, and Shlwapi.h header file.

    #pragma comment(lib, "shlwapi.lib")
    #include <shlwapi.h>
    

    the function returns a BOOL value and can be called like so:

    if( PathFileExists("C:\\path\\to\\your\\file.ext") )
    {
        // do something
    }
    
    0 讨论(0)
  • 2020-12-13 12:39

    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.

    0 讨论(0)
  • 2020-12-13 12:41

    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.

    0 讨论(0)
  • 2020-12-13 12:42

    What Operating System/platform?

    On Linux/Unix/MacOSX, you can use fstat.

    On Windows, you can use GetFileAttributes.

    Usually, there is no portable way of doing this with standard C/C++ IO functions.

    0 讨论(0)
  • 2020-12-13 12:42

    if you are on unix then access() can tell you if it's readable. However if ACL's are in use, then it gets more complicated, in this case it's best to just open the file with ifstream and try read.. if you cannot read then the ACL may prohibit reading.

    0 讨论(0)
  • 2020-12-13 12:46

    Since C++11 it's possible to use implicit operator bool instead of good():

    ifstream my_file("test.txt");
    if (my_file) {
      // read away
    }
    
    0 讨论(0)
提交回复
热议问题