copendir 是一个用于打开目录的函数,它通常与 readdir 和 closedir 一起使用,以便在 C 语言程序中遍历目录结构
sudo apt-get update
sudo apt-get install build-essential
list_directory.c 的新文件,并在其中编写以下代码:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("/path/to/directory"); // 替换为你要搜索的目录路径
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc 编译器编译代码:gcc list_directory.c -o list_directory
./list_directory
这将显示指定目录中的所有文件和子目录。如果你想搜索特定类型的文件,可以在 while 循环中添加条件检查。例如,要仅列出所有 .txt 文件,可以这样做:
if (entry->d_type == DT_REG && strstr(entry->d_name, ".txt")) {
printf("%s\n", entry->d_name);
}
这将仅显示扩展名为 .txt 的文件。