考研 408 × 求职面试
知识点 · Linux · 基础
每日一题 · Linux
解析
面试小贴士 · Linux
代码实现 · C
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void find_file(const char *path, const char *name) {
DIR *dir = opendir(path);
if (!dir) return;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
char full[1024];
snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
if (strcmp(entry->d_name, name) == 0) printf("%s\n", full);
struct stat st;
if (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) {
find_file(full, name); // 递归进入子目录,类似 find 的实时遍历
}
}
closedir(dir);
}
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "用法: %s 目录 文件名\n", argv[0]);
return 1;
}
find_file(argv[1], argv[2]); // 示例: ./find /home test.txt
return 0;
}