c - 如何在 C 的目录/子目录中查找文件的实例?

标签 c linux

所以我有一个程序,通过传递的文件名,我需要查找/打开当前目录和所有子目录中存在的所有具有该名称的文件。

我不知道子目录的名称。我不关心他们的名字或任何其他文件,我只需要能够打开所有具有传递名称的文件。

谢谢!

最佳答案

这是一个使用 ntfw() 的例子。

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf){
    char *fileName = "findMe.txt";
    /* fpath holds the full path of the file from the specified starting directory */
    if ( strstr(fpath, fileName) ){
        printf("Match found!\n");
    }
    return 0;
}

int main(int argc, char **argv){
    /* If a starting directory isn't specified, use the current dir */
    if (nftw((argc < 2) ? "." : argv[1], display_info, 20, 0) == -1) {
        perror("nftw");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

关于c - 如何在 C 的目录/子目录中查找文件的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40775912/

相关文章:

android - 错误 : getaddrinfo ENOTFOUND localhost

c++ - 如何在 cout 上使用 isatty(),或者我可以假设 cout == 文件描述符 1?

linux - 在 .*sh 文件中启动一个新的 shell

c - 为什么这个简单的 PWM 在 xc8 中不起作用

c++ - C 和 C++ 标准之间的关系是什么?

c - 在 r-pi raspbian 上编译 c 程序时出错

c++ - C/C++ : How should preprocessor directive work on macros argument list?

linux - 如何在bash中实现两个echo语句输出到同一行

linux - Bash - 将 2 个 ssh 调用合并为 1 个(带有可选和强制命令)

c - "Cannot allocate memory"在 C 中使用 shmat 命令的共享内存问题