在 Debian 系统中,readdir
是一个用于读取目录内容的系统调用。以下是一些与 readdir
相关的实用技巧:
使用 opendir
和 readdir
函数:
opendir()
打开一个目录。readdir()
来读取目录中的每个条目。closedir()
关闭目录。#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
过滤特定类型的文件:
entry->d_type
来检查文件类型,并根据需要过滤文件。if (entry->d_type == DT_REG) {
printf("Regular file: %s\n", entry->d_name);
} else if (entry->d_type == DT_DIR) {
printf("Directory: %s\n", entry->d_name);
}
处理隐藏文件:
readdir()
会返回包括隐藏文件(以点开头的文件)在内的所有文件。if (entry->d_name[0] != '.') {
printf("%s\n", entry->d_name);
}
按特定顺序排序:
readdir()
返回的文件顺序是不确定的,如果需要按特定顺序(如字母顺序)处理文件,可以在读取后对文件名进行排序。// 假设 file_names 是一个包含所有文件名的数组
qsort(file_names, num_files, sizeof(file_names[0]), strcmp);
处理符号链接:
lstat()
而不是 stat()
来检查文件是否为符号链接,并根据需要处理。struct stat statbuf;
if (lstat(entry->d_name, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISLNK(statbuf.st_mode)) {
printf("Symbolic link: %s\n", entry->d_name);
}
获取文件的详细信息:
stat()
函数可以获取文件的详细信息,如大小、修改时间等。struct stat statbuf;
if (stat(entry->d_name, &statbuf) == -1) {
perror("stat");
continue;
}
printf("Size: %ld\n", statbuf.st_size);
printf("Last modified: %s", ctime(&statbuf.st_mtime));
通过这些技巧,你可以更灵活地使用 readdir
来处理目录内容。