[英]S_IFMT and S_IFREG undefined with -std=c11 or -std=gnu11
[英]what is S_IFMT in UNIX system programming?
我正在學習系統調用,因此正在編寫代碼以使用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);
}
S_IFMT
是文件類型的位掩碼(請參見man stat
)
直接與mystat.st_mode
( mystat.st_mode & S_IFMT
)按位與( mystat.st_mode & S_IFMT
)意味着僅考慮確定文件類型(常規文件,套接字,塊或char設備等)所涉及的位。
對mystat.st_mode與按位取反的位掩碼( mystat.st_mode & ~S_IFMT
)進行按位AND意味着忽略上述位,只保留那些需要確定文件許可權的位(該命令下方的9行)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.