逐行读取文件只返回最后一行(Reading file line by line returns just the last line)

编程入门 行业动态 更新时间:2024-10-27 05:29:19
逐行读取文件只返回最后一行(Reading file line by line returns just the last line)

这非常奇怪 - 我从文件中获取行,将它们打印到屏幕上,并将它们存储在数组中。 将它们打印到屏幕上时,一切看起来都很好,但在数组中,每个元素都设置为文件的最后一行。

文件看起来像这样:

DarkMatter Fire Water Air Earth Plasma Wind

这是我的代码:

char *rooms[7]; FILE *roomFile = fopen("rooms.txt", "r"); char name[20]; for(i=0; i<7; i++) { fgets(name, sizeof name, roomFile); rooms[i] = name; printf("%s", rooms[i]); } for(i=0; i<7; i++) { printf("%s\n", rooms[i]); }

在文件循环中打印rooms[i]时,一切看起来都很好,但是一旦我尝试打印房间数组后,每个元素都会被设置为wind 。 这怎么可能?

输出:

DarkMatter Fire Water Air Earth Plasma Wind Wind Wind Wind Wind Wind Wind Wind

This is incredibly strange - I'm getting the lines from a file, printing them out to the screen, and storing them in array. When printing them out to the screen everything looks fine, but in the array every element is set to the last line of the file.

File looks like this:

DarkMatter Fire Water Air Earth Plasma Wind

This is my code:

char *rooms[7]; FILE *roomFile = fopen("rooms.txt", "r"); char name[20]; for(i=0; i<7; i++) { fgets(name, sizeof name, roomFile); rooms[i] = name; printf("%s", rooms[i]); } for(i=0; i<7; i++) { printf("%s\n", rooms[i]); }

When printing rooms[i] during the file loop everything looks fine, but once I try to print the rooms array afterwards, every element is set to wind. How is this even possible?

Output:

DarkMatter Fire Water Air Earth Plasma Wind Wind Wind Wind Wind Wind Wind Wind

最满意答案

更换

rooms[i] = name;

//rooms[i] = name; rooms[i] = malloc(20); strcpy(rooms[i], name);

原因

声明rooms[i] = name; 只是指示指针rooms[i]等于指针(或数组) name 。 所以有效的每个rooms[0], rooms[1], rooms[2]包含name的地址。 在for循环的每次迭代中, name都被复制为不同的字符串。 但是由name指出的地址,因此rooms所有元素都保持不变。

Replace

rooms[i] = name;

with

//rooms[i] = name; rooms[i] = malloc(20); strcpy(rooms[i], name);

Reason

The statement rooms[i] = name; simply instructs that the pointer rooms[i] is equal to the pointer (or array) name. So effectively each of rooms[0], rooms[1], rooms[2] holds the address of name. In each iteration of your for loop, name gets copied with a different string. But the address pointed to by name and hence all the elements of rooms remain the same.

更多推荐

本文发布于:2023-08-03 06:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1384134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   Reading   file   line   returns

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!