小编Srd*_*jan的帖子

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

所以我想编写一个程序来遍历目录并将文件名添加到名为“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; …
Run Code Online (Sandbox Code Playgroud)

c arrays directory file

3
推荐指数
1
解决办法
6574
查看次数

标签 统计

arrays ×1

c ×1

directory ×1

file ×1