提问人:Parker 提问时间:2/21/2022 最后编辑:Parker 更新时间:2/22/2022 访问量:494
将行从文件复制到 char *array[]?
Copy lines from file to char *array[]?
问:
嗨,在这里需要一点帮助。我有一个有 5 行的文件,我想把这些行放入一个类型的数组中,但我无法弄清楚为什么以下内容不起作用。char *lines[5];
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("name.txt", "r");
char *str;
char *list[5];
int i = 0;
while (fgets(str, 100, fp) != NULL) // read line of text
{
printf("%s", str);
strcpy(list[i], str);
i++;
}
}
答:
2赞
villanif
2/22/2022
#1
正如评论者所说,您需要创建一个足够大小的数组(只不过是内存中的一个空间)来存储您的字符串。解决问题的一种方法如下,请注意注释:
#include <stdio.h>
#include <string.h>
int lines(FILE *file); //try to format the code according to some standard
int main(void) {
FILE *fp = fopen("name.txt", "r");
char list[5][100]; //make sure you allocate enough space for your message
// for loop is more elegant than while loop in this case,
// as you have an index which increases anyway.
// also, you can make sure that files with more than 5 lines
// do not break your program.
for(int i = 0; i<5 ;++i )
{
if(fgets(list[i], 100, fp) == NULL){
break;
}
//list[i] is already a string, you don't need an extra copy
printf("%s", list[i]);
}
}
评论
1赞
Chris
2/22/2022
您甚至可以将调用包含在循环中的条件中。fgets
for (int i = 0; i < 5 && fgets(list[i], 100, fp) != NULL; ++i ) { printf("%s", list[i]); }
评论
list[i]
是未初始化的指针。您需要用 或 将其指向某个地方。malloc
strdup
char list[5][100];
str
fgets
fgets
str
fgets
5
list