在Linux中,readdir
函数用于读取目录中的文件和子目录。它通常与opendir
和closedir
函数一起使用。要获取文件属性,可以使用stat
函数。以下是一个简单的示例,展示了如何使用这些函数读取目录中的文件并获取它们的属性:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
// 打开目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 读取目录中的条目
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(.)和上级目录(..)
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 获取文件属性
if (stat(entry->d_name, &file_stat) == -1) {
perror("stat");
closedir(dir);
return EXIT_FAILURE;
}
// 输出文件名和文件类型
printf("File: %s\n", entry->d_name);
printf("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("Unknown\n");
}
// 输出其他文件属性
printf("Size: %ld bytes\n", file_stat.st_size);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序首先打开当前目录(.
),然后使用readdir
函数读取目录中的每个条目。对于每个条目,它使用stat
函数获取文件属性,并根据文件类型输出相应的信息。最后,它关闭目录并退出。
注意:在实际应用中,可能需要处理更多的错误情况和边缘情况。这个示例仅用于演示如何使用readdir
和stat
函数。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1362541.html