这是我第一次使用posix;我包括:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
我有这个片段。
stat(pathname, &sb);
if ((sb.st_mode & S_IFMT) == S_IFREG) {
/* Handle regular file */
}
但是在Gentoo上使用GCC 4.8.3,如果我用-std=c99、-std=c11、-std=gnu99或-std=gnu11编译,我会得到这样的错误:
error: ‘S_ISFMT’ undeclared (first use in this function)
如果我省略了-std=*,我不会得到任何错误。但我也想要-std=c99的所有功能(比如关键字restrict or for(int;;)等)我如何编译我的代码?
发布于 2015-02-17 01:52:18
现代的POSIX兼容系统需要提供S_IFMT
和S_IFREG
值。POSIX.1-1990是POSIX.1-1990,它似乎是您的机器上的标准。
在任何情况下,每个与POSIX兼容的系统都提供了允许您检查文件类型的macros。这些宏等效于掩码方法。
因此,在您的示例中,只需编写S_ISREG(sb.st_mode)
,而不是(sb.st_mode & S_IFMT) == S_IFREG
。
发布于 2015-02-24 06:53:04
在源代码中,将#define _BSD_SOURCE
或#define _XOPEN_SOURCE
放在任何#include
之前。要了解其工作原理,请在sys/stat.h
中的#define S_IFMT __S_IFMT
上方查看,然后在feature_test_macros(7)
手册页中查看。
发布于 2018-12-31 20:35:29
K&R2提供:
#define S_IFMT 0160000 /* type of file: */
#define S_IFDIR 0040000 /* directory */
在第8.6章中,示例-列出目录。
我不鼓励使用这个解决方案,此外,我希望一些专家可以教我们它是正确的还是没有实现的,利弊和替代方案等等。提前谢谢你!
MWE示例。
根所有者代码创建者:https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_8:Exercise_5
a.out
S_IFMT
:S_IFDIR
MWE:
/* these defines at beginning to highlight them */
#define S_IFMT 0160000 /* type of file: */
#define S_IFDIR 0040000 /* directory */
/*
Modify the fsize program to print the other information contained in the inode entry.
*/
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <pwd.h>
#define MAX_PATH 1024
#ifndef DIRSIZ
#define DIRSIZ 14
#endif
void dirwalk( char *dir,void (*fcn)(char *)){
char name[MAX_PATH];
struct dirent *dp;
DIR *dfd;
if((dfd = opendir(dir))==NULL){
puts("Error: Cannot open Directory");
return;
}
puts(dir);
// Get each dir entry
while((dp=readdir(dfd)) != NULL){
// Skip . and .. is redundant.
if(strcmp(dp->d_name,".") == 0
|| strcmp(dp->d_name,"..") ==0 )
continue;
if(strlen(dir)+strlen(dp->d_name)+2 > sizeof(name))
puts("Error: Name too long!");
else{
sprintf(name,"%s/%s",dir,dp->d_name);
// Call fsize
(*fcn)(name);
}
}
closedir(dfd);
}
void fsize(char *name){
struct stat stbuf;
if(stat(name,&stbuf) == -1){
puts("Error: Cannot get file stats!");
return;
}
if((stbuf.st_mode & S_IFMT) == S_IFDIR){
dirwalk(name,fsize);
}
struct passwd *pwd = getpwuid(stbuf.st_uid);
//print file name,size and owner
printf("%81d %s Owner: %s\n",(int)stbuf.st_size,name,pwd->pw_name);
}
int main(int argc,char *argv[]){
if(argc==1)
fsize(".");
else
while(--argc>0)
fsize(*++argv);
return 0;
}
https://stackoverflow.com/questions/28547271
复制相似问题