在Ubuntu中,opendir
函数是用于打开目录的,而不是直接用于查找文件。如果你想要使用opendir
来查找文件,你需要结合其他函数,如readdir
,来遍历目录中的条目,并检查每个条目是否是你想要的文件。
以下是一个简单的示例,展示了如何使用opendir
和readdir
来查找特定类型的文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <directory> <filename_pattern>\n", argv[0]);
return EXIT_FAILURE;
}
const char *dir_path = argv[1];
const char *filename_pattern = argv[2];
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Skip current and parent directory entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct the full path to the entry
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, entry->d_name);
// Get the file information
struct stat statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
// Check if it's a regular file and matches the pattern
if (S_ISREG(statbuf.st_mode) && strstr(entry->d_name, filename_pattern)) {
printf("Found file: %s\n", full_path);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
find_files.c
。gcc -o find_files find_files.c
./find_files /path/to/directory filename_pattern
例如,如果你想在/home/user/documents
目录中查找所有以.txt
结尾的文件,可以运行:
./find_files /home/user/documents .txt
opendir
函数用于打开一个目录。readdir
函数用于读取目录中的条目。stat
函数用于获取文件的信息。S_ISREG
宏用于检查一个条目是否是常规文件。strstr
函数用于检查文件名是否包含指定的模式。通过这种方式,你可以使用opendir
和readdir
来遍历目录并查找特定类型的文件。