The Pointer The Pointer - 1 month ago 25
C Question

What is S_ISREG() and what does it do?

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 that is 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.

Answer

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 or man fstat 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 */
       }