2017-10-25 14 views
-2

プログラムに入力されたファイルの種類を数えようとしています。したがって、echo.cのCソースを入力すると、echo.hはHeaderとなります。しかし、echo/rootのようにディレクトリを入力した場合は、directoryタイプとしてカウントされますが、現在はexeタイプとしてカウントされます。私は他のすべての仕事を手に入れました。stat()を使って、argvがディレクトリであるかどうかを調べる方法を考えようとしています。相続人stat()を使ってコマンドライン引数がディレクトリであるかどうかをチェックする方法?

私がこれまでにしたもの:

#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; 
} 
関連する問題