我将尝试将c文件的每一行添加到一个数组中。文件.txt的内容如下:
first.c
second.c
third.c
fourth.c
我希望我的代码能够打印出这些行,将每一行添加到我的数组中,并且打印出数组中的每个条目。现在它已经正确执行了前面的部分,但是它只将 fourth.c 添加到了数组中。有人能告诉我我的代码哪里出了问题吗?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i=0;
int numProgs=0;
char* programs[50];
char line[50];
FILE *file;
file = fopen("files.txt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
//check to be sure reading correctly
printf("%s", line);
//add each filename into array of programs
programs[i]=line;
i++;
//count number of programs in file
numProgs++;
}
//check to be sure going into array correctly
for (int j=0 ; j<numProgs+1; j++) {
printf("\n%s", programs[j]);
}
fclose(file);
return 0;
}
sizeof(line)
? - CinCoutsizeof line
也是正确的。 - Jabberwocky