Verifying Directory Existence in Unix Using System Calls
In Unix systems, querying the existence of a directory is essential for various file management tasks. Unlike opendir() which returns an error if a directory doesn't exist, other methods provide more precise directory verification.
stat() and lstat() for Directory Checking
POSIX systems offer two functions, stat() and lstat(), to ascertain the existence and type of an object specified by a pathname. While stat() follows symbolic links, lstat() examines the symbolic link itself.
The following code snippet demonstrates how to use stat() to check for directory existence:
#include <sys/stat.h> struct stat sb; if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode)) { // ...it is a directory... }
S_IS* Macros for File Type Identification
If stat() succeeds, S_ISDIR() can be used to determine if the file is a directory. Other S_IS* macros allow for the identification of various file types:
The above is the detailed content of How to Check if a Directory Exists in Unix Using System Calls?. For more information, please follow other related articles on the PHP Chinese website!