2017-10-25 26 views
-2

임 프로그램에 입력 된 파일의 유형을 계산하려고합니다. 따라서 echo.c의 C 소스를 입력하면 echo.h는 Header가됩니다. 그러나 디렉토리를 입력하면 echo/root과 같이 directory 유형으로 계산되어야하지만 지금은 exe 유형으로 계산됩니다. 필자는 stat()을 사용하여 argv이 디렉토리인지 확인하는 방법을 알아 내려고 노력했습니다.stat()를 사용하여 명령 줄 인수가 디렉토리인지 확인하는 방법?

는 Heres는 지금까지 무엇을 :

#include <sys/stat.h> 

int main(int argc, char* argv[]){ 
int cCount = 0; 
int cHeadCount = 0; 
int dirCount = 0; 


for(int i = 1; i < argc; i++){ 

    FILE *fi = fopen(argv[i], "r"); 

    if(!fi){ 
     fprintf(stderr,"File not found: %s", argv[i]); 
    } 
    else{ 

    struct stat directory; 
    //if .c extension > cCount++ 
    //else if .h extension > cHeadCount++ 

    else if(stat(argv[i], &directory) == 0){ 
     if(directory.st_mode & S_IFDIR){ 
      dirCount++; 
     } 
    } 

    } 

    //print values, exit 
} 
} 
+1

당신이 지금까지 가지고있는 것을 보여주세요 – JackVanier

+0

'man 2 stat'에서 당신에게 불분명 한 점은 무엇입니까? – Evert

+0

'man 2 stat'을 읽으셨습니까? – dlmeetei

답변

0

지불 세심한주의를 문서에 : stat(2)

또한 파일을 여는 이유를 확실입니다. 당신은 그렇게 할 필요가없는 것처럼 보입니다.

#include <stdio.h> 

// Please include ALL the files indicated in the manual 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <unistd.h> 

int main(int argc, char** argv) 
{ 
    int dirCount = 0; 

    for (int i = 1; i < argc; i++) 
    { 
    struct stat st; 
    if (stat(argv[i], &st) != 0) 
     // If something went wrong, you probably don't care, 
     // since you are just looking for directories. 
     // (This assumption may not be true. 
     // Please read through the errors that can be produced on the man page.) 
     continue; 

    if (S_ISDIR(st.st_mode)) 
     dirCount += 1; 
    } 

    printf("Number of directories listed as argument = %d.\n", dirCount); 

    return 0; 
}