2012-02-10 6 views
1

직접 반환이C 리눅스 find 명령의 리턴 경로를 직접

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

같은
보다는 무언가 또는 통해 실행 일부 유사한 명령으로 경로를 찾기 명령을 사용하여 얻을 수있는 간단한 방법이있다 c가 경로를 반환합니까?

+1

아니요, 반환 값은 find (1) 호출의 종료 값입니다. 당신은 출력물을 파싱해야합니다. – tbert

+0

나는 발견 http://stackoverflow.com/questions/671461/how-can-i-execute-external-commands-in-c-linux –

답변

2

내가 nftw 사용하는 것이 좋습니다()는 단순 들어

#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); 
} 

내가 현재의 검색을 시작합니다 (gcc test.c -o test 컴파일) 개념의 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 

깊이 -이다 :

./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 

인쇄 (기존과 같은 파일이없는 가정) 먼저으로 플래그를 조정하면 쉽게 바뀔 수 있습니다. nftw

+0

일이, 내가했다 두려워 멋지다 오전 어떤 명령/문법의 측면에서 좀 더 간단한 것을 물어 보았습니다. 나는 빠졌을 때 문자열을 문자열로 반환합니다. 그것은 tbert에 의해 분명 해졌다. –

0

이것을 수행하기 위해 dup 또는 dup2 호출을 시도 할 수 있습니까?

+0

http://stackoverflow.com/questions/8093315/nftw-different-on-bsd –

관련 문제