How to test a file or directory exists in C++?

How to test a path (a file or directory exists) in C++?

In Bash, the [ -f ] and [ -d ] tests can test whether a file or a directory exist. What are the corresponding C++ ways for these tests?

To test whether a file or dir (a path) exists, you may call stat() against the path and check its return value.

#include <sys/stat.h>

bool IsPathExist(const std::string &s)
  struct stat buffer;
  return (stat (s.c_str(), &buffer) == 0);
Leave a Reply

Your email address will not be published. Required fields are marked *