I wrote a code to read files
What is wrong in the following code I am always getting last filename if I print any arrayItem
#include <stdio.h>
#include <string.h>
char **get_files()
{
FILE *fp;
int status;
char file[1000];
char **files = NULL;
int i = 0;
/* Open the command for reading. */
fp = popen("ls", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
//exit;
}
while (fgets(file, sizeof(file)-1, fp) != NULL) {
files = (char **)realloc(files, (i + 1) * sizeof(char *));
//files[i] = (char *)malloc(sizeof(char));
files[i] = file;
i++;
}
printf("%s", files[0]);
return files;
}
int main()
{
char **files = NULL;
int i =0 ;
files = get_files("");
}