C:将目录中的文件列表存储到数组中

Srd*_*jan 3 c arrays directory file

所以我想编写一个程序来遍历目录并将文件名添加到名为“filesList”的字符串数组中。但问题是,当它完成时,数组中的每个元素都是目录中最后一个文件的名称。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
int n=0, i=0;
DIR *d;
struct dirent *dir;
d = opendir(argv[1]);

//Determine the number of files
while((dir = readdir(d)) != NULL) {
    if ( !strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..") )
    {

    } else {
        n++;
    }
}
rewinddir(d);

char *filesList[n];

//Put file names into the array
while((dir = readdir(d)) != NULL) {
    if ( !strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..") )
    {}
    else {
        filesList[i]= dir->d_name;
        i++;
    }
}
rewinddir(d);

for(i=0; i<=n; i++)
    printf("%s\n", filesList[i]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

16t*_*ons 5

这是因为您没有为 filesList 各个元素分配内存。您为其分配“dir->d_name”(基本上将 filesList 的每个元素指向单个 d_name)。您应该为其中的每个条目执行 malloc。

else {
        filesList[i] = (char*) malloc (strlen(dir->d_name)+1);
        strncpy (filesList[i],dir->d_name, strlen(dir->d_name) );
        i++;
    }
Run Code Online (Sandbox Code Playgroud)

  • 如果可用的话,您也可以只使用“strdup()”。[它由 POSIX 标准化。](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strdup.html) (2认同)