Home > Backend Development > C++ > How to Determine if a Directory Exists in Unix?

How to Determine if a Directory Exists in Unix?

DDD
Release: 2024-11-06 12:22:02
Original
703 people have browsed it

How to Determine if a Directory Exists in Unix?

Checking Directory Existence in Unix

In Unix, determining the existence of a directory is essential for various operations. Unlike opendir() which only reveals the non-existence of a directory upon an error, there are system calls specifically designed to ascertain the presence of a directory.

To address this need, POSIX systems offer two functions: stat() and lstat(). Both functions provide information about the specified pathname, including its type. However, stat() follows symbolic links while lstat() does not.

To check if a directory exists using stat():

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    // Directory exists
}
Copy after login

The macro S_ISDIR() confirms the file type as a directory. Similarly, other file types can be checked using corresponding S_IS* macros.

Conclusion:

stat() and lstat() provide a convenient and comprehensive way to determine the existence and type of a file or directory in Unix, enabling seamless handling of file system-related operations.

The above is the detailed content of How to Determine if a Directory Exists in Unix?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template