在Linux中,readdir
函数用于读取目录中的文件和子目录。要实现目录遍历,你需要遵循以下步骤:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
使用opendir()
函数打开一个目录。它需要一个目录路径作为参数,并返回一个DIR
指针,如果出错则返回NULL
。
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
使用readdir()
函数读取目录中的条目。它需要一个DIR
指针作为参数,并返回一个指向struct dirent
的指针,如果出错或到达目录末尾则返回NULL
。
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 处理目录条目
}
struct dirent
结构体包含有关目录条目的信息,如文件名、inode号等。你可以使用entry->d_name
获取文件名。
printf("Entry: %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_path>\n", argv[0]);
return EXIT_FAILURE;
}
const char *path = argv[1];
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("Entry: %s\n", entry->d_name);
}
closedir(dir);
return EXIT_SUCCESS;
}
编译并运行此程序,传入一个目录路径作为参数,它将输出该目录中的所有文件和子目录。