在Linux中,readdir
函数用于读取目录中的条目。但是,readdir
本身并不直接提供文件的属性信息。要获取文件属性信息,你需要使用其他函数,如stat
、lstat
或fstat
。
以下是一个简单的示例,展示了如何使用opendir
、readdir
和stat
函数来获取目录中文件的属性信息:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.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;
}
// 使用stat函数获取文件属性信息
if (stat(entry->d_name, &file_stat) == -1) {
perror("stat");
closedir(dir);
return EXIT_FAILURE;
}
// 输出文件名和文件类型
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));
}
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序首先打开当前目录,然后使用readdir
函数读取目录中的每个条目。对于每个条目,它使用stat
函数获取文件的属性信息,并输出文件名、大小和最后修改时间。注意,这个示例仅适用于UNIX-like系统,如Linux。