c linux find命令直接返回路径

时间:2012-02-10 11:43:27

标签: c linux file-io

是否有一种简单的方法可以直接使用find命令并将路径作为返回值 而不是像这样的东西

            sprintf(inputPath, "find -name %s",fileNameList[i]);
            fpop=popen(inputPath, "r");
            fgets(inputPath, sizeof(inputPath)-1, fpop) ;
            pclose(fpop);

或一些类似的命令,当通过c执行时返回路径?

2 个答案:

答案 0 :(得分:2)

我建议使用nftw()自己进行查找,用C编写代码并不多。简单的概念证明(用gcc test.c -o test编译)

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

static int    s_argc;
static char** s_argv;

static int
display_info(const char *fpath, const struct stat *sb,
             int tflag, struct FTW *ftwbuf)
{
    int matched = 0, i;
    for (i=0; i<s_argc; i++)
    {
        const char* match = strstr(fpath, s_argv[i]);
        matched |= (match && *match 
                && (strlen(match) == strlen(s_argv[i]))           // matches at end
                && ((match == s_argv[i]) || (match[-1] == '/'))); // is full basename
    }

    if (matched)
    {
        printf("%-3s %2d %7jd   %-40s %d %s\n",
                (tflag == FTW_D) ?   "d"   : (tflag == FTW_DNR) ? "dnr" :
                (tflag == FTW_DP) ?  "dp"  : (tflag == FTW_F) ?   "f" :
                (tflag == FTW_NS) ?  "ns"  : (tflag == FTW_SL) ?  "sl" :
                (tflag == FTW_SLN) ? "sln" : "???",
                ftwbuf->level, (intmax_t) sb->st_size,
                fpath, ftwbuf->base, fpath + ftwbuf->base);
    }

    return 0;           /* To tell nftw() to continue */
}

int
main(int argc, char *argv[])
{
    s_argc = argc-1;
    s_argv = argv+1;

    int flags = FTW_DEPTH | FTW_PHYS;

    if (nftw(".", display_info, 20, flags) == -1)
    {
        perror("nftw");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

为简单起见,我从当前工作目录(“。”)开始搜索。像这样使用:

./test target.txt b c

什么都不打印(假设你没有这样的文件)

mkdir -pv a/b/c/{d,e,f,g}/subdir
touch a/b/c/{e,g}/subdir/target.txt
./test target.txt b c

现在打印:

f    6       0   ./a/b/c/e/subdir/target.txt              17 target.txt
f    6       0   ./a/b/c/g/subdir/target.txt              17 target.txt
dp   3       0   ./a/b/c                                  6 c
dp   2       0   ./a/b                                    4 b

您可以看到排序是深度优先,但可以通过将标志调整为nftw

来轻松更改

答案 1 :(得分:0)

您可以尝试使用dup或dup2来实现此目的吗?

相关问题