What is `S_ISREG()`, and what does it do?

c, linux, macos, operating-system, unix

Solution

S_ISREG() is a macro used to interpret the values in a stat-struct, as returned from the system call stat(). It evaluates to true if the argument(The st_mode member in struct stat) is a regular file.

See `man stat`, `man fstat` or `man inode` (link to inode man page) for further details. Here's the relevant part of the man page:

   Because tests of the above form are common, additional macros are defined by POSIX to allow the test of the file type in st_mode to be written more concisely:

       S_ISREG(m)  is it a regular file?

       S_ISDIR(m)  directory?

       S_ISCHR(m)  character device?

       S_ISBLK(m)  block device?

       S_ISFIFO(m) FIFO (named pipe)?

       S_ISLNK(m)  symbolic link?  (Not in POSIX.1-1996.)

       S_ISSOCK(m) socket?  (Not in POSIX.1-1996.)

   The preceding code snippet could thus be rewritten as:

       stat(pathname, &sb);
       if (S_ISREG(sb.st_mode)) {
           /* Handle regular file */
       }

Problem

I came across the macro `S_ISREG()` in a C program that retrieves file attributes. Unfortunately, there isn't any basic information about this macro online. There are some more advanced discussions on it, but they go beyond what I'm looking for. What is `S_ISREG()`, and what does it do? In the context of a program that retrieves file attributes, what purpose does it serve, and exactly what does it do? Thank you.

Original source