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

前端 未结 3 1714
时光说笑
时光说笑 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 09:01

    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 */
           }
    

提交回复
热议问题