2016-12-24 4 views
0

ディレクトリ内のすべてのファイルをリストする次のコードがあります。私は各ep-> d_nameを配列に追加しようとしていますが、これまで試みてきたことはすべて機能していません。私はどのように進めるべきですか?Cの配列にep-> d_nameを挿入する方法

#include <stdio.h> 
#include <sys/types.h> 
#include <dirent.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <string.h> 
#include <fcntl.h> 
#include <time.h> 
#include <errno.h> 
#include <sys/stat.h> 
#include <sys/times.h> 
#include <sys/wait.h> 

int main (void){ 
    DIR *dp; 
    struct dirent *ep; 
    dp = opendir("./"); 
    int count = 0; 

    char *fileNames = calloc(256, sizeof(char)); 

    if(dp != NULL){ 
     while(ep = readdir(dp)){ 
      printf("%s\n", ep->d_name); 
      count = count+1; 
     } 
     for (int i=0; i<count; i++){ 
     fileNames[i] = ep->d_name; 
     } 
     closedir(dp); 
    }else{ 
     perror("Couldn't open the directory"); 
    } 
    return 0; 
} 

コードのこのビットは変更されませんする必要があります。

int main (void){ 

    DIR *dp; 
    struct dirent *ep; 
    dp = opendir("./"); 

    if(dp != NULL){ 
     while(ep = readdir(dp)){ 
      printf("%s\n", ep->d_name); 
     } 
     closedir(dp); 
    }else{ 
     perror("Couldn't open the directory"); 
    } 
    return 0; 

} 
+0

あなたは何を試してみましたか?例を挙げてください。あなたのコードのどこにでも宣言された配列は見えません。私たちにもっと情報を与えてください。 – Bargros

+1

'fileNames'変数が単一の文字列であることを意味しましたか?文字列の配列にしたくないのですか? –

+0

ええ、それぞれの文字列は実際にはメモリ内のその文字列のデータへのポインタなので、複数の文字列を格納したい場合は、以下のようにchar *またはchar **へのポインタを持たなければなりません。 manページの 'scandir'の定義を見ると、さらに混乱します。自動的に割り当てられるchar **のアドレスを保存するので、2番目の要素は実際にchar **またはchar **の_pointer_です。 * '。そして、私はそれが割り当てた 'char **'配列の_addressを格納するために 'scandir 'を必要とするchar **の_address_を渡します。 –

答えて

1

なぜむしろエントリを反復処理するよりも、あなたのためのアレイを提供するscandirを使用していませんか?

これは私のために働くようだ:

$ cat t.c 
#include <stdio.h> 
#include <sys/types.h> 
#include <dirent.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <string.h> 
#include <fcntl.h> 
#include <time.h> 
#include <errno.h> 
#include <sys/stat.h> 
#include <sys/times.h> 
#include <sys/wait.h> 

int main (void){ 
    DIR *dp; 
    struct dirent **list; 

    int count = scandir("./", &list, NULL, alphasort); 
    if(count < 0){ 
     perror("Couldn't open the directory"); 
     exit(1); 
    } 
    printf("%u items in directory\n", count); 
    for(int i=0; i<count;i++){ 
      printf("%s\n", list[i]->d_name); 
    } 
    return 0; 
} 

は私を与える:

docker run -it --rm -v `pwd`/t.c:/t.c gcc bash -c "gcc -o t t.c && ./t" 
24 items in directory 
. 
.. 
.dockerenv 
bin 
boot 
dev 
etc 
home 
lib 
lib64 
media 
mnt 
opt 
proc 
root 
run 
sbin 
srv 
sys 
t 
t.c 
tmp 
usr 
var 
+0

元のコードを変更しないでください。 – krm

+0

あなたのコードはうまくいかないので、動作させるには変更する必要があります –

関連する問題