在Linux中,readdir函数用于读取目录中的文件和子目录
以下是一个简单的示例,展示了如何使用readdir和自定义排序函数对目录中的文件进行排序:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
// 自定义比较函数
int compare(const void *a, const void *b) {
const char *str1 = *(const char **)a;
const char *str2 = *(const char **)b;
return strcmp(str1, str2);
}
int main() {
DIR *dir;
struct dirent *entry;
char *files[100];
int count = 0;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
// 读取目录中的文件和子目录
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // 只添加普通文件
files[count] = malloc(strlen(entry->d_name) + 1);
strcpy(files[count], entry->d_name);
count++;
}
}
// 使用自定义比较函数对文件名进行排序
qsort(files, count, sizeof(char *), compare);
// 打印排序后的文件名
for (int i = 0; i < count; i++) {
printf("%s\n", files[i]);
free(files[i]);
}
closedir(dir);
return 0;
}
在这个示例中,我们首先使用opendir打开当前目录,然后使用readdir读取目录中的文件和子目录。我们将普通文件的文件名存储在一个字符串数组中。接下来,我们使用qsort函数和自定义比较函数compare对文件名进行排序。最后,我们打印排序后的文件名,并释放分配的内存。
注意:这个示例仅用于演示目的,实际应用中可能需要处理更多的错误情况和边界条件。