I have this code. This is the file content
nasa.txt
news1.txt
file11.txt
mixed.txt
planets.txt
file21.txt
info31.txt
This is the code
FILE *fp = fopen(collectionFilename, "r");
char url[MAX_WORD 1];
char *urls[MAX_WORD 1];
while(fscanf(fp, "%s", url) == 1){
urls[index ] = url;
}
for(int i = 0; i < index; i ){
printf("%s\n", urls[i]);
}
fclose(fp);
I want the code to read in the file names and store them into my urls array. However my printf
statement at the end prints info31.txt 7 times and I'm a bit confused as to why this happens.
Thank you!
CodePudding user response:
From your code there are two steps in the loop
fscanf(fp, "%s", url)
will read string and write the string tourl
urls[index ] = url;
will assignurls[index]
to point tourl
and increaseindex
by one
The key point is that in step 2, you just repeat the same thing to every elements in urls
-- pointing them to url
, which is why you get the same URL from urls
. You never copy the characters from url
to somewhere else and fscanf
just keep using the same buffer for input in every iteration.