在 CentOS 系統中,readdir
函數用于讀取目錄內容。默認情況下,readdir
返回的目錄項是按照文件名排序的。如果你想要自定義排序規則,可以使用 dirent.h
中定義的 readdir
函數,并結合其他函數來實現。
以下是一個簡單的示例,展示如何使用 readdir
和 qsort
函數來自定義目錄項的排序規則:
#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;
// 按照字符串長度排序
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
if (len1 < len2) {
return -1;
} else if (len1 > len2) {
return 1;
} else {
return strcmp(str1, str2);
}
}
int main() {
DIR *dir;
struct dirent *entry;
char path[] = "/path/to/your/directory";
char **files = NULL;
int count = 0;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 讀取目錄項并存儲到數組中
while ((entry = readdir(dir)) != NULL) {
files = realloc(files, sizeof(char *) * (count + 1));
files[count] = strdup(entry->d_name);
count++;
}
closedir(dir);
// 使用 qsort 對目錄項進行排序
qsort(files, count, sizeof(char *), compare);
// 輸出排序后的目錄項
for (int i = 0; i < count; i++) {
printf("%s\n", files[i]);
free(files[i]);
}
free(files);
return EXIT_SUCCESS;
}
在這個示例中,我們首先使用 opendir
打開目錄,然后使用 readdir
讀取目錄項并將其存儲到一個字符串數組中。接著,我們使用 qsort
函數和自定義的比較函數 compare
對目錄項進行排序。最后,我們輸出排序后的目錄項并釋放內存。
你可以根據需要修改 compare
函數來實現不同的排序規則。