在Debian中,你可以使用readdir
函数来读取目录中的文件,并使用qsort
函数对它们进行排序。以下是一个简单的示例,展示了如何使用这些函数对目录中的文件进行排序:
sudo apt-get update
sudo apt-get install build-essential
sort_files.c
的C文件,并将以下代码粘贴到其中:#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;
int count = 0;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) {
files = realloc(files, sizeof(char *) * (count + 1));
files[count] = malloc(strlen(entry->d_name) + 1);
strcpy(files[count], 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]);
}
free(files);
return EXIT_SUCCESS;
}
这个程序会读取当前目录中的所有文件(不包括子目录),将它们存储在一个字符串数组中,然后使用qsort
函数对它们进行排序。最后,它会打印排序后的文件名列表。
sort_files.c
:gcc -o sort_files sort_files.c
./sort_files
这将显示当前目录中的所有文件,按字母顺序排序。如果你想对其他目录中的文件进行排序,只需将opendir(".")
中的.
替换为目标目录的路径即可。