linux用c查看文件类型
时间: 2023-10-11 09:07:08 浏览: 54
可以使用stat函数获取文件信息中的st_mode字段,然后使用S_ISREG、S_ISDIR、S_ISCHR、S_ISBLK、S_ISFIFO、S_ISLNK、S_ISSOCK宏判断文件类型。示例代码如下:
```
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
return 1;
}
struct stat st;
if (stat(argv[1], &st) == -1) {
perror("stat");
return 1;
}
if (S_ISREG(st.st_mode)) {
printf("Regular file\n");
} else if (S_ISDIR(st.st_mode)) {
printf("Directory\n");
} else if (S_ISCHR(st.st_mode)) {
printf("Character device\n");
} else if (S_ISBLK(st.st_mode)) {
printf("Block device\n");
} else if (S_ISFIFO(st.st_mode)) {
printf("FIFO/pipe\n");
} else if (S_ISLNK(st.st_mode)) {
printf("Symbolic link\n");
} else if (S_ISSOCK(st.st_mode)) {
printf("Socket\n");
} else {
printf("Unknown file type\n");
}
return 0;
}
```