Reputation: 35
So I want to write a program that goes through a directory and adds file names into an array of strings called "filesList". But the problem is, when it finishes, every element in the array is the name of the last file in the directory. Here's the code:
#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;
}
Upvotes: 3
Views: 6920
Reputation: 725
It is because you are not allocating memory for your filesList individual elements. You are assisgning it the "dir->d_name" (basically pointing each element of your filesList to a single d_name). You should be doing a malloc for each entry in there.
else {
filesList[i] = (char*) malloc (strlen(dir->d_name)+1);
strncpy (filesList[i],dir->d_name, strlen(dir->d_name) );
i++;
}
Upvotes: 5