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