Linux中如何用copendir实现文件搜索
导读:在 Linux 中,opendir( 函数用于打开一个目录流,以便后续使用 readdir( 函数读取目录中的条目。结合这两个函数,可以实现一个简单的文件搜索功能。以下是一个示例代码,展示如何使用 opendir( 和 readdir...
在 Linux 中,opendir()
函数用于打开一个目录流,以便后续使用 readdir()
函数读取目录中的条目。结合这两个函数,可以实现一个简单的文件搜索功能。以下是一个示例代码,展示如何使用 opendir()
和 readdir()
来遍历目录并查找特定类型的文件:
#include <
stdio.h>
#include <
stdlib.h>
#include <
string.h>
#include <
dirent.h>
#include <
sys/stat.h>
void search_files(const char *path, const char *extension) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
// 打开目录
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
// 遍历目录中的条目
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和上级目录的特殊条目
if (strcmp(entry->
d_name, ".") == 0 || strcmp(entry->
d_name, "..") == 0) {
continue;
}
// 构建完整的文件路径
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->
d_name);
// 获取文件信息
if (stat(full_path, &
statbuf) == -1) {
perror("stat");
continue;
}
// 检查是否为目录,如果是则递归搜索
if (S_ISDIR(statbuf.st_mode)) {
search_files(full_path, extension);
}
// 检查文件扩展名是否匹配
else if (strstr(entry->
d_name, extension) != NULL) {
printf("Found file: %s\n", full_path);
}
}
// 关闭目录
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <
directory>
<
extension>
\n", argv[0]);
return EXIT_FAILURE;
}
search_files(argv[1], argv[2]);
return EXIT_SUCCESS;
}
说明:
opendir()
: 打开一个目录流。readdir()
: 读取目录流中的下一个条目。stat()
: 获取文件或目录的信息。S_ISDIR()
: 检查文件是否为目录。strstr()
: 检查文件名中是否包含指定的扩展名。
使用方法:
编译并运行程序,传入要搜索的目录路径和文件扩展名。例如:
gcc -o search_files search_files.c
./search_files /path/to/search .txt
这个程序会递归地搜索指定目录及其子目录中的所有 .txt
文件,并打印出它们的完整路径。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Linux中如何用copendir实现文件搜索
本文地址: https://pptw.com/jishu/716978.html