readdir 函數本身并不提供直接按名稱排序的功能。它只是簡單地返回目錄中的文件和子目錄列表。要按名稱排序這些文件和子目錄,你需要在調用 readdir 之后對結果進行排序。
以下是一個使用 C 語言的示例,展示了如何使用 readdir 和 qsort 函數按名稱排序目錄中的文件和子目錄:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
DIR *dir;
struct dirent *entry;
char *files[100];
int count = 0;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
files[count] = strdup(entry->d_name);
count++;
}
closedir(dir);
qsort(files, count, sizeof(char *), compare);
for (int i = 0; i < count; i++) {
printf("%s\n", files[i]);
free(files[i]);
}
return EXIT_SUCCESS;
}
這個示例首先打開當前目錄(.),然后使用 readdir 讀取目錄中的所有文件和子目錄。接著,它使用 qsort 函數對文件名進行排序。最后,它打印排序后的文件名并釋放分配的內存。
請注意,這個示例假設目錄中的文件和子目錄數量不超過 100。在實際應用中,你可能需要根據需要調整數組大小或使用動態內存分配。