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

前端 未结 3 1756
时光说笑
时光说笑 2021-02-05 08:30

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 ar

3条回答
  •  耶瑟儿~
    2021-02-05 08:55

    It tests the st_mode member of the stat structure retrieved using the stat() function to determine whether the file is a regualar 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.

提交回复
热议问题