copendir
函数用于打开一个目录流,以便读取目录中的内容。要实现目录遍历,通常会结合使用 opendir
、readdir
和 closedir
函数。以下是一个示例代码,展示了如何使用这些函数来遍历目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
// 打开目录
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
// 读取目录中的条目
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和父目录的特殊条目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 打印文件或目录名
printf("%s\n", entry->d_name);
}
// 关闭目录
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
包含头文件:
#include <stdio.h>
:标准输入输出库。#include <stdlib.h>
:标准库,用于 EXIT_SUCCESS
和 EXIT_FAILURE
。#include <dirent.h>
:目录操作库,包含 opendir
、readdir
和 closedir
函数。#include <string.h>
:字符串操作库,用于 strcmp
函数。定义函数 list_directory_contents
:
const char *path
:要遍历的目录路径。opendir
打开目录,如果失败则打印错误信息并返回。readdir
读取目录中的每个条目,直到 NULL
表示没有更多条目。.
)和父目录(..
)的特殊条目。closedir
关闭目录。主函数 main
:
list_directory_contents
函数,传入目录路径。使用以下命令编译和运行程序:
gcc -o listdir listdir.c
./listdir /path/to/directory
将 /path/to/directory
替换为你想要遍历的目录路径。程序将输出该目录中的所有文件和子目录。