Jary Jary - 1 year ago 92
C Question

Checking if a directory exists in Unix (system call)

I am not able to find a solution to my problem online.

I would like to call a function in Unix, pass in the path of a directory, and know if it exists.

returns an error if a directory does not exist, but my goal is not to actually open, check the error, close it if no error, but rather just check if a file is a directory or not.

Is there any convenient way to do that please?

Answer Source

There are two relevant functions on POSIX systems: stat() and lstat(). These are used to find out whether a pathname refers to an actual object that you have permission to access, and if so, the data returned tells you what type of object it is. The difference between stat() and lstat() is that if the name you give is a symbolic link, stat() follows the symbolic link (or links if they are chained together) and reports on the object at the end of the chain of links, whereas lstat() reports on the symbolic link itself.

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode))
    ...it is a directory...

If the function indicates it was successful, you use the S_ISDIR() macro from <sys/stat.h> to determine whether the file is actually a directory.

You can also check for other file types using other S_IS* macros:

  • S_ISDIR — directory
  • S_ISREG — regular file
  • S_ISCHR — character device
  • S_ISBLK — block device
  • S_ISLNK — symbolic link
  • S_ISSOCK — socket

(Some systems provide a few other file types too; S_ISDOOR is available on Solaris, for example.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download