C <sys/stat.h> 查找文件类型

C <sys/stat.h> Find file type

我为项目创建了自己的 ls 命令,并使用 "st_mode" 变量来查找文件权限,但我不使用宏。

例如: st_mode = 16877

我把它转换成八进制:

st_mode = 40755

我保留最后三个字符并获得我的许可。

但是当我尝试查找文件类型时,我尝试使用前两个字符,但它们并没有真正帮助我... 所以我想知道我是否可以使用前两个字符来查找文件的类型(Link,文件夹,...)。如果我不能,我应该使用什么来查找文件的类型

感谢您的帮助。

根据 POSIX <sys/stat.h> documentation:

The following macros shall be provided to test whether a file is of the specified type. The value m supplied to the macros is the value of st_mode from a stat structure. The macro shall evaluate to a non-zero value if the test is true; 0 if the test is false.

S_ISBLK(m)
    Test for a block special file.
S_ISCHR(m)
    Test for a character special file.
S_ISDIR(m)
    Test for a directory.
S_ISFIFO(m)
    Test for a pipe or FIFO special file.
S_ISREG(m)
    Test for a regular file.
S_ISLNK(m)
    Test for a symbolic link.
S_ISSOCK(m)
    Test for a socket.

是的,您可以将这两种方法与预定义的宏一起使用,如下所示,打开 stat() 系统调用的手册页,上面写着

S_IFMT     0170000   bit mask for the file type bit fields

st_modeS_IFMT& 也是如此,您将获得文件类型

                struct stat v;
                stat(file,&v);  
                switch (v.st_mode & S_IFMT) // type of file
                {

                        case S_IFBLK:  printf("b");                 break;
                        case S_IFCHR:  printf("c");                 break;
                        case S_IFDIR:  printf("d");                 break;
                        case S_IFIFO:  printf("p");                 break;
                        case S_IFLNK:  printf("l");                 break;
                        case S_IFREG:  printf("-");                 break;
                        case S_IFSOCK: printf("s");                 break;
                        default:       printf("unknown?");          break;
                }

如果你不想使用宏,那么首先找出files每种类型的st_mode值,然后编写逻辑。例如 regular filest_mode 的值为 10664permission 的最后 3 位数字(664),写下 10664 的二进制你会知道 15th位已设置 st.mode >> 15 。同样找到不同类型文件的st_mode值并分析。

if( ( v.st_mode >> 15 & 1) && ( v.st_mode >> 14 & 1) ) 
                printf("Socket File\n"); 
        else if( ( v.st_mode >> 15 & 1) && ( v.st_mode >> 13 & 1) )
                printf("Symbolic Link File\n");
        else if( v.st_mode >> 15 & 1) 
                printf("Regular File\n");
        else if((v.st_mode >> 14 & 1) && (v.st_mode >> 13 & 1) )
                printf("Block Dev File\n");
        else if(v.st_mode >> 14 & 1) 
                printf("Directory File\n");
        else if(v.st_mode >> 13 & 1)
                printf("Char Dev File\n");
        else if(v.st_mode >> 12 & 1)
                printf("FIFO/PIPE File\n");

希望对您有所帮助。