【问题标题】:what is S_IFMT in UNIX system programming?UNIX系统编程中的S_IFMT是什么?
【发布时间】:2015-10-05 15:10:17
【问题描述】:

我正在学习系统调用,因此正在编写代码以使用 C 语言实现 ls。代码有效,但我无法理解

val=(mystat.st_mode & ~S_IFMT)

在下面给出的代码中?我理解其余的代码。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <time.h>

int main(int argc, char* argv[])
{
    DIR *mydir;
    struct dirent *myfile;
    struct stat mystat;

    mydir = opendir(argv[1]);
    char buf[512];
    while((myfile = readdir(mydir)) != NULL)
    {
        struct tm *time_stamp=localtime(&mystat.st_mtime);
        sprintf(buf, "%s/%s", argv[1], myfile->d_name);
        stat(buf, &mystat);
        //stat(myfile->d_name, &mystat);   
        mode_t val;

        val=(mystat.st_mode & ~S_IFMT);
        (val & S_IRUSR) ? printf("r") : printf("-");
        (val & S_IWUSR) ? printf("w") : printf("-");    
        (val & S_IXUSR) ? printf("x") : printf("-");
        (val & S_IRGRP) ? printf("r") : printf("-");
        (val & S_IWGRP) ? printf("w") : printf("-");
        (val & S_IXGRP) ? printf("x") : printf("-");
        (val & S_IROTH) ? printf("r") : printf("-");
        (val & S_IWOTH) ? printf("w") : printf("-");
        (val & S_IXOTH) ? printf("x") : printf("-");
        printf("\t%d",mystat.st_nlink);
        printf("\t%d",mystat.st_uid);
        printf("\t%d",mystat.st_gid); 
        printf("\t%d",mystat.st_size);
        char buffer[80];
        strftime(buffer,10,"%b",time_stamp);

        printf("\t%4d %s %2d ", time_stamp->tm_year+1900,buffer,time_stamp->tm_mday);
        printf(" %s\n", myfile->d_name);
    }
    closedir(mydir);
}

【问题讨论】:

    标签: c linux operating-system system-calls


    【解决方案1】:

    S_IFMT 是文件类型的位掩码(请参阅man stat

    直接与mystat.st_mode (mystat.st_mode &amp; S_IFMT) 进行位与运算意味着只考虑确定文件类型(常规文件、套接字、块或字符设备等)所涉及的位

    使用按位取反位掩码 (mystat.st_mode &amp; ~S_IFMT) 对 mystat.st_mode 进行按位与操作意味着忽略上面解释的位,只保留需要确定文件权限的位(该命令下方的 9 行)。

    【讨论】:

    • 在接下来的 9 行中,我们执行说 (val & S_IRUSR) ,其中 S_IRUSR 表示 256(100000000),所以其他位将自动关闭..那么按位与运算需要什么~S_IFMT 然后关闭那些不必要的位?
    • mode_t st_mode 定义为 4 字节(16 位);上面的4个用于文件类型,另外12个用于文件模式(这12个中的低9个用于文件权限);要确保将高 4 位设置为零,您可以执行 st_mode AND 0000111111111111 这正是 ~S_IFMT
    猜你喜欢
    • 2011-05-29
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2011-04-04
    • 2020-07-31
    • 1970-01-01
    • 2013-09-13
    相关资源
    最近更新 更多