Home > Backend Development > C++ > body text

How to Check Directory Existence in Unix Using System Calls?

Barbara Streisand
Release: 2024-11-07 13:09:03
Original
842 people have browsed it

How to Check Directory Existence in Unix Using System Calls?

Checking Directory Existence in Unix: A Comprehensive Guide Using System Calls

Problem:

In Unix, how can one determine the existence of a directory using a system call without opening it or handling related errors?

Answer:

POSIX systems provide two essential functions for this purpose: stat() and lstat(). These functions allow you to ascertain whether a pathname reflects a valid accessible object and retrieve information about its type.

Key Differences Between stat() and lstat():

  • stat(): Follows symbolic links and provides information about the final destination.
  • lstat(): Provides information about the symbolic link itself, regardless of any targets it may point to.

Implementation Using stat():

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    // True if pathname is a directory
}
Copy after login

Additional File Type Verification:

Using the S_IS* macros from , you can verify other file types beyond directories:

  • 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 Directory Existence 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