2010-01-28 2 views
3

C를 사용하여 각 경로에 파일 이름을 연결하여 stat()를 호출 할 수 있지만 strcat를 내부에서 사용하려고 할 때 루프는 이전 파일 이름을 다음 파일과 연결합니다.경로로 파일을 연결하여 C로 전체 경로 가져 오기

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

int main(int argc, char *argv[]) { 
struct stat buff; 

int status; 

if (argc > 1) { 
    status = stat(argv[1], &buff); 
    if (status != -1) { 
    if (S_ISDIR(buff.st_mode)) { 
    DIR *dp = opendir(argv[1]); 
    struct dirent *ep; 
    char* path = argv[1]; 
    printf("Path = %s\n", path); 

    if (dp != NULL) { 
     while (ep = readdir(dp)) { 
     char* fullpath = strcat(path, ep->d_name); 
     printf("Full Path = %s\n", fullpath); 
    } 
    (void) closedir(dp); 
    } else { 
     perror("Couldn't open the directory"); 
    } 
} 

    } else { 
    perror(argv[1]); 
    exit(1); 
    } 
} else { 
    perror(argv[0]]); 
       exit(1); 
} 

return 0; 
} 
+2

가이 코드에 구문 오류가 있습니다; "perror (argv [0]]);" 하나가 너무] 많습니다. 실제 코드를 복사하여 붙여 넣으십시오. –

답변

9

처럼 전체 경로 때마다 새로운 캐릭터를 만들어보십시오. 비록 당신이하더라도, 당신은 단지 argv[1]을 가지고 있기 때문에, 그것에 strcat()을하는 것은 이전에 당신이 가지고 있던 무엇이든지에 계속 덧붙이려고 할 것입니다.

다른 미묘한 버그가 있습니다. 디렉토리 이름과 파일 이름은 대부분의 시스템에서 경로 구분 기호 /으로 구분해야합니다. 코드에 추가하지 마십시오.

은 while 루프의 외부에서이를 해결하려면 :

당신은 당신의 while 루프에서이 작업을 수행해야
size_t arglen = strlen(argv[1]); 

:

/* + 2 because of the '/' and the terminating 0 */ 
char *fullpath = malloc(arglen + strlen(ep->d_name) + 2); 
if (fullpath == NULL) { /* deal with error and exit */ } 
sprintf(fullpath, "%s/%s", path, ep->d_name); 
/* use fullpath */ 
free(fullpath); 
+0

sprintf (fullpath ("% s/% s"경로, ep-> d_name) 대신'sprintf '(전체 경로, "% s/% s"경로, ep-> d_name) ? –

+0

@ m-ric, 수정 해 주셔서 감사합니다. –

0

당신을 argv [의 크기를 증가하려고해서는 안 ... [1] 루프시는 argv를 수정,하지만 난 오랫동안 C에 근무 한 적이없는, 그래서 나는 매우 혼란 스러워요 1] 그것을 strcat'ing하여 (그리고 그것을 전혀 변경 나쁜 생각입니다) - 그 정의되지 않은 동작이 발생합니다. 대신 argv [1]을 적절한 크기의 버퍼에 복사하고 다음 작업을 수행하십시오.

char path[1000]; // or some suitable size; 
strcpy(path, argv[1]); 
+0

strcpy를 의미하지 않습니까? 경로는 0이 채워지지 않을 수도 있습니다. – Mark

+0

@Mark Correct - 바보 오자. –

1

여기서는 복사 할 메모리가 있습니까? 경로는 스택에 할당되어 필요한 인수를 포함합니다. 예를 들어 메모리를 직접 할당합니다. 중지 생산 코드 자체 함수 역시 등으로

char path[1024] ; // or some other number 
strcpy(path, argv[1]); 
// then separator 
strcat(path, "/") ; // or "\\" in Windows 
strcat(path, ep->d_name); 

오버 플로우

0

문제는 라인

char* fullpath = strcat(path, ep->d_name); 

path 현재 파일의 이름을 추가 계속 것입니다. 당신은 argv[i]을 수정해서는 안

char* fullpath = calloc(strlen(path) + strlen(ep->d_name) + 1); 
strcat(fullpath, path); 
strcat(fullpath, ep->d_name); 
/* .. */ 
free(fullpath); 
관련 문제