This program should traverse a directory and save the file names into an array so I can manipulate data within the files. The problem is that the program prints the name of the files in the first loop, but it only saves the last file name in the array. Below is a copy of the code...The commented lines are other things that I have tried, but I get the same output. This is a small part of many programs I must write for my research, so I know the name of the directory and how many files are in the directory.
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
int main(void)
{ FILE *fp;
DIR *d;
struct dirent *dir;
char *filenames[8];
//char *filenames = malloc(sizeof *filenames);
int i=0;
int a;
d = opendir("revisions");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
//strcpy((char*)(long)filenames[i],(void *)(dir->d_name));
//*(char**)&filenames[i]=gets(dir->d_name);
filenames[i]=(dir->d_name);
printf("%s",filenames[i]);
//printf("%s",*(char**)&filenames[i]);
printf("\n");
i++;
}
printf("\n");
closedir(d);
}
for (a = 2; a < i; a++){
//printf(*(char**)&filenames[a]);
printf("%s",filenames[a]);
printf("\n");
}
return(0);
}
The output is as follows:
.
..
v1
v2
v3
v4
v5
v6
v6
v6
v6
v6
v6
v6
I was expecting:
.
..
v1
v2
v3
v4
v5
v6
v1
v2
v3
v4
v5
v6