在Linux中,readdir
函数用于读取目录中的条目。当你使用readdir
函数时,它会返回一个指向dirent
结构体的指针,该结构体包含了目录条目的信息,如文件名、文件类型等。要处理文件属性,你可以使用stat
函数来获取文件的详细信息。
以下是一个简单的示例,展示了如何使用readdir
和stat
函数来处理文件属性:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char path[1024];
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
// 打开目录
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
// 读取目录中的条目
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和上级目录
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建文件的完整路径
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 获取文件的详细信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 处理文件属性
printf("File: %s\n", entry->d_name);
printf("Size: %ld bytes\n", file_stat.st_size);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
printf("File type: ");
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file\n");
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory\n");
} else if (S_ISCHR(file_stat.st_mode)) {
printf("Character device\n");
} else if (S_ISBLK(file_stat.st_mode)) {
printf("Block device\n");
} else if (S_ISFIFO(file_stat.st_mode)) {
printf("FIFO\n");
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("Socket\n");
} else {
printf("Other\n");
}
}
// 关闭目录
closedir(dir);
return 0;
}
这个示例程序接受一个目录作为命令行参数,然后使用readdir
函数读取目录中的条目。对于每个条目,它使用stat
函数获取文件的详细信息,并根据文件类型打印相应的属性。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1296668.html