在Linux中,有多种函数可用于遍历目录
示例代码:
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
示例代码:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return alphasort(a, b);
}
int main() {
struct dirent **namelist;
int n;
n = scandir(".", &namelist, NULL, compare);
if (n < 0) {
perror("scandir");
return 1;
}
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
return 0;
}
示例代码:
#include <glob.h>
#include <stdio.h>
int main() {
glob_t globbuf;
int ret;
ret = glob("*", GLOB_TILDE, NULL, &globbuf);
if (ret != 0) {
fprintf(stderr, "glob error: %d\n", ret);
return 1;
}
for (size_t i = 0; i < globbuf.gl_pathc; i++) {
printf("%s\n", globbuf.gl_pathv[i]);
}
globfree(&globbuf);
return 0;
}
比较:
根据实际需求和场景选择合适的目录遍历函数。