如何将ep-> d_name插入C中的数组中

问题描述:

我有下面的代码列出目录中的所有文件。我试图将每个ep-> d_name添加到数组中,但到目前为止,我所尝试过的所有功能都没有奏效。我应该如何继续?如何将ep-> d_name插入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 *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 *或char **的指针,如下所示。当你查看手册页中的'scandir'定义时会更加困惑 - 因为它保存了它自动分配的char **的地址,其第二个元素实际上是一个指向char **或char **的_pointer_ *'。然后,我传入char **的_address_,我希望'scandir'存储它分配的char **数组的_address_。 –

为什么不使用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

以及你的代码不起作用,所以要使它工作,你必须改变它 –