在 CentOS 系統中,你可以使用 readdir
函數來實現自定義排序。readdir
函數用于讀取目錄中的文件和子目錄。為了實現自定義排序,你需要使用 dirent.h
頭文件,并結合 qsort
函數對目錄項進行排序。
以下是一個簡單的示例,展示了如何使用 readdir
和 qsort
實現自定義排序:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
// 自定義比較函數
int compare(const void *a, const void *b) {
struct dirent **dir1 = (struct dirent **)a;
struct dirent **dir2 = (struct dirent **)b;
return strcmp((*dir1)->d_name, (*dir2)->d_name);
}
int main() {
DIR *dir;
struct dirent *entry;
struct dirent **namelist;
// 打開目錄
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
// 讀取目錄中的所有項
int count = 0;
while ((entry = readdir(dir)) != NULL) {
namelist = realloc(namelist, sizeof(struct dirent *) * (count + 1));
namelist[count] = entry;
count++;
}
// 關閉目錄
closedir(dir);
// 使用 qsort 對目錄項進行排序
qsort(namelist, count, sizeof(struct dirent *), compare);
// 輸出排序后的目錄項
for (int i = 0; i < count; i++) {
printf("%s\n", namelist[i]->d_name);
}
// 釋放內存
free(namelist);
return 0;
}
在這個示例中,我們首先使用 opendir
函數打開當前目錄,然后使用 readdir
函數讀取目錄中的所有項。接下來,我們使用 qsort
函數對目錄項進行排序,自定義比較函數 compare
根據文件名進行排序。最后,我們輸出排序后的目錄項并釋放內存。
你可以根據需要修改 compare
函數來實現不同的排序方式。例如,你可以根據文件大小、修改時間等進行排序。