It tests the st_mode
member of the stat
structure retrieved using the stat()
function to determine whether the file is a regular file (i.e. on on disk or mass storage rather than say a directory, socket, symbolic link for example.
struct stat sb;
if( stat( file_path, &sb) != -1) // Check the return value of stat
{
if( S_ISREG( sb.st_mode ) != 0 )
{
printf( "%s is a file", file_path ) ;
}
else
{
printf( "%s is not a file", file_path ) ;
}
}
The st_mode
member contains 4 bits masked by S_IFMT
(0170000). The values of these bits are:
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
so the macro S_ISREG mighte be defined thus:
#define S_ISREG( m ) (((m) & S_IFMT) == S_IFREG)
Since it is a macro you can look at its actual definition in the header file sys/stat.h
. In the GNU header it is defined this:
#define __S_ISTYPE(mode, mask) (((mode) & __S_IFMT) == (mask))
...
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
which is essentially the same at my simplified version.
S_ISREG
was just a small part. The example in the man page forstat()
shows testing ofst_mode
- these macros simply wrap that test into boolean results.man 2 stat
works perfectly on linux.