在Linux中,有多种方法可以遍历目录
opendir() 函数用于打开一个目录流,返回一个指向DIR结构的指针。readdir() 函数用于读取目录流中的条目。这两个函数通常与closedir()一起使用,以关闭目录流。
示例代码:
#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;
}
scandir() 函数用于读取目录中的条目,并将它们存储在一个动态分配的数组中。每个数组元素都是一个指向dirent结构的指针,其中包含文件名和其他信息。scandir() 还需要一个比较函数,用于对结果进行排序。
示例代码:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
struct dirent **namelist;
int n;
n = scandir(".", &namelist, NULL, compare);
if (n < 0) {
perror("scandir");
return 1;
}
while (n--) {
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
return 0;
}
glob() 函数用于匹配符合特定模式的文件名。它将匹配的文件名存储在一个动态分配的数组中,并返回数组的长度。与scandir()类似,glob() 也需要一个比较函数。
示例代码:
#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;
}
比较:
根据具体需求和场景,可以选择最适合的方法来遍历Linux中的目录。