2

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;
}
Srdjan
  • 25
  • 1
  • 4

1 Answers1

4

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++;
    }
16tons
  • 675
  • 5
  • 14
  • 2
    You could also just use `strdup()` if available. [It is standardized by POSIX.](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strdup.html) – Andrew Henle Jan 14 '17 at 18:28
  • Thanks, it works! Can you tell me why you used strncpy() instead of strcpy()? – Srdjan Jan 14 '17 at 18:50
  • 1
    It's a good practice to always use strncpy instead of strcpy. read more http://stackoverflow.com/a/1258556/7407065 – 16tons Jan 14 '17 at 18:53