Home > Backend Development > C++ > How to Check if a Directory Exists in Unix Using System Calls?

How to Check if a Directory Exists in Unix Using System Calls?

Barbara Streisand
Release: 2024-11-08 00:30:03
Original
309 people have browsed it

How to Check if a Directory Exists in Unix Using System Calls?

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...
}
Copy after login

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:

  • S_ISDIR - Directory
  • S_ISREG - Regular file
  • S_ISCHR - Character device
  • S_ISBLK - Block device
  • S_ISFIFO - FIFO
  • S_ISLNK - Symbolic link
  • S_ISSOCK - Socket

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template