我想知道如何正确读取文件并将每一行放入 C 中的数组字符串中。
我有一个文件,上面写着以下内容
one
two
three
four
我尝试写这样的东西:
int read_file(FILE *fp){
char readLine[MAX_LEN];
char *myarray[20];
int counter =0;
int i =0;
while(fgets(readLine,MAX_LEN,fp) != NULL){
myarray[counter] = readLine;
counter++;
}
/*printing the array*/
while(i<counter){
printf("%d %s",i,myarray[i]);
i++;
}
}
主要内容是这样的
int main(){
FILE *fp;
fp = fopen("my.txt","r");
if(fp == NULL){
fprintf(stderr,"File does not exist");
return EXIT_FAILURE;
}
read_file(fp);
}
但是,在打印时我得到:
four
four
four
four
即使我使用 printf("%s",myarr[2])
打印,我仍然得到 4
有人知道问题出在哪里吗?
最佳答案
当您覆盖用于接受输入的缓冲区时,您确实需要复制该行(通过 strdup()
):
int read_file(FILE *fp){
char readLine[MAX_LEN];
char *myarray[20]; // Note char pointer!
int i, counter = 0;
while (counter < 20 && fgets(readLine,MAX_LEN,fp) != NULL) { // Note limit!
myarray[counter] = strdup(readLine);
counter++;
}
/*printing the array*/
for (i = 0; i < counter; i++)
printf("%d %s",i,myarray[i]);
/* free the lines */
for (i = 0; i < counter; i++)
free(myarray[i]);
}
关于c - 将文件读取到数组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18356901/