Hello,
I have a rather simple program, which reads a string from file and stores it in a char array. While reading the file, each line is saved in the array properly, but when I exit the loop and print the array again, it prints only the last entry. There is probably something silly that I have not taken into account, but I am not able to figure it out.
Here is the code:
Code:
#include <stdio.h>
int main(int argc, char ** argv)
{
char **input_list;
int num_list=0;
char temp_list[1024] ="";
char line[4096];
FILE *wlist = NULL;
if (argc<=1)
{
fprintf(stderr, "Usage: {-list <File listing the strings> \n", argv[0]);
exit(-1);
}
while(argc>1)
if (strcmp(argv[1], "-list")==0)
{
fprintf(stdout, "foo\n");
input_list = (char **)calloc(4096, sizeof(char *));
if ((wlist = fopen(argv[2], "r"))!=NULL)
{
num_list = 0;
while(fgets(line, sizeof(line), wlist)!=NULL)
{
sscanf(line, "%s", &(temp_list));
input_list[num_list]= (char *)calloc(4096, sizeof(char));
input_list[num_list]= (temp_list);
fprintf(stdout, "Read string %s\n",input_list[num_list]);
num_list++;
}
input_list[num_list] = NULL;
fclose(wlist);
fprintf(stdout, "Read %d strings\n", num_list);
}
argc--;argv++;
argc--;argv++;
}
int i;
for(i=0;i<num_list;i++)
{
fprintf(stdout, "String %s\n", input_list[i]);
}
free(input_list);
}
The input list file looks like this:
"a"
"b"
"c"
"d"
And the output is:
foo
Read waveform "a"
Read waveform "b"
Read waveform "c"
Read waveform "d"
Read 4 waveforms
Waveform "d"
Waveform "d"
Waveform "d"
Waveform "d"
When I reprint the input_waveforms_list array, it prints the last line that it read for four times. Kindly let me know what is wrong with the code or a better way to write it.
Thanks.