2016-09-23 30 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

明らかに、あなたのプログラムは<パターンに格納されているもの>というエントリを出力し、2つの異なるエントリには同じ名前を付けることができないため、1つのエントリだけを出力します。 – immibis

+0

注意: '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

私はプログラムの現在の状態を反映するために質問を更新しました。 –

関連する問題