在 Linux 中,readdir
函数用于读取目录的内容。要使用 readdir
读取子目录,你需要遵循以下步骤:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
其中 path
是你要读取的目录的路径。
使用 readdir
函数读取目录中的每个条目。readdir
返回一个指向 struct dirent
的指针,该结构包含有关目录条目的信息。
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
在完成目录读取后,使用 closedir
函数关闭目录。
closedir(dir);
这是一个完整的示例,展示了如何使用 readdir
读取子目录:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译并运行此程序,传入一个目录路径作为参数,它将打印该目录中的所有文件和子目录。