我正在尝试使用 stat(2)确定 argv[i] 是否是常规文件、目录或符号链接(symbolic link)。从 stat(2)
手册页中我不明白两件事:
stat(2)
采用的第二个参数是什么(即 buf arg)int stat(const char *path, struct stat *buf);
如何使用返回值来确定它是 reg 文件、目录还是符号链接(symbolic link)?
最佳答案
要回答第一个问题,您可以取消引用 stat
结构体的实例,并将取消引用的值传递给 stat()
以填充实例的字段值:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
/* ... */
struct stat foo;
const char *path = "/a/b/c";
/* test the result of stat() to make sure it ran correctly */
if (stat(path, &foo) != 0) {
fprintf(stderr, "something went wrong with stat()\n");
exit(EXIT_FAILURE);
}
/* now do stuff with foo; e.g. from docs: */
switch (foo.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("directory\n"); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("symlink\n"); break;
case S_IFREG: printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
要回答第二个问题,请参阅您链接到的文档:
The following POSIX macros are defined to check
the file type using the st_mode field:
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.)
如果 stat()
成功,st_mode
字段就会填充,因此您可以将该结果传递给上面列出的宏:
if (S_ISREG(foo.st_mode)) {
fprintf(stderr, "whatever foo points to is a regular file\n");
}
else {
fprintf(stderr, "whatever foo points to is something else\n");
}
您应该首先测试 stat()
的结果,以确保 st_mode
和其他字段中有可用的值。再次,请引用文档,它实际上写得很好,或者参见上面的代码片段。
关于c - 检测文件类型(常规文件、目录、符号链接(symbolic link)等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25586516/