2016-09-23 1 views
0

디렉토리를 검색하고 명령 줄 인수와 일치하는 내용을 나열하는 프로그램을 작성하는 동안 문제가 발생할 수 있습니다. 알아 낸다.while 루프와 C에서 readdir()을 사용하지 않는 경우

문자열이 일치하는지 확인하기 위해 while 루프 내에 if 문을 넣었습니다. 그러나 문제는 디렉터리의 마지막 항목 만 가져 오는 것입니다. if 문을 주석 처리하면 전체 디렉토리가 잘 인쇄되고 문자열은 정확하게 일치하지만 둘 다 수행하지는 않습니다.

친구가 스택과 관련이 있다고 제안했지만 각 읽기 후에 인쇄 중이므로 그 이유를 알 수 없습니다.

DIR *dirPos; 
struct dirent * entry; 
struct stat st; 
char *pattern = argv[argc-1]; 

//---------------------- 
//a few error checks for command line and file opening 
//---------------------- 

//Open directory 
if ((dirPos = opendir(".")) == NULL){ 
    //error message if null 
} 

//Print entry 
while ((entry = readdir(dirPos)) != NULL){ 
    if (!strcmp(entry->d_name, pattern)){ 
     stat(entry->d_name, &st); 
     printf("%s\t%d\n", entry->d_name, st.st_size); 
    } 
} 
+2

정확하게 문제를 이해하면 일부 regext API를 사용하고 싶습니다. strcmp는 패턴과 일치하지 않지만 문자열과 정확하게 일치합니다. – PnotNP

+0

명백히 프로그램은 하나의 엔트리 만 인쇄합니다. 왜냐하면 <패턴에 저장된 모든 것>이라는 엔트리를 인쇄하고 두 개의 다른 엔트리가 같은 이름을 가질 수 없기 때문입니다. – immibis

+0

Note :'stat()'는 전체 경로가 필요합니다. – joop

답변

0

entry은 포인터로서 정의되어야한다. struct dirent* entry. 나는 C에서 이것을 컴파일하고 잘 동작한다.

#include <dirent.h> 
#include <string.h> 
#include <stdio.h> 
#include <sys/types.h> 
#include <sys/stat.h> 

int main(int argc, char **argv) 
{ 
    DIR *dirPos; 
    struct dirent* entry; 
    struct stat st; 
    char *pattern = argv[argc-1]; 

    //---------------------- 
    //a few error checks for command line and file opening 
    //---------------------- 

    //Open directory 
    if ((dirPos = opendir(".")) == NULL){ 
     //error message if null 
    } 

    //Print entry 
    while ((entry = readdir(dirPos)) != NULL){ 
     if (!strcmp(entry->d_name, pattern)){ 
      stat(entry->d_name, &st); 
      printf("%s\t%d\n", entry->d_name, st.st_size); 
     } 
    } 

    return 0; 
} 
+0

spitballing하는 동안 포인터 입력을 변경했습니다. 그것을 다시 되돌려 놓는 것을 잊어 버렸습니다. 같은 결과. * .c는 디렉토리의 마지막 C 파일을 리턴하고 다른 파일은 리턴하지 않습니다. * .h는 헤더 파일과 동일합니다. * .c * main.c ~ –

+0

을 반환합니다. 프로그램의 현재 상태를 반영하도록 제 질문을 업데이트했습니다. –

관련 문제