gpt4 book ai didi

c - 读取文件并将每一行保存到 C 中的变量

转载 作者:太空宇宙 更新时间:2023-11-04 08:57:49 25 4
gpt4 key购买 nike

我正在使用 fgetc 和 fopen 读取 C 中的文件。我想在变量中获取第一行,在单独的变量中获取第二行,如下所示:

f = fopen("textfile", "r");

if (!f) {
printf("error");
} else {
loop until end of newline and save entire line to a variable
1st line ==> line1
2nd line ==> line2
}

所以如果文本文件有:

hello world
goodbye world

line1 = " Hello World "line2 = "再见世界"

我正在考虑循环直到\n 但我应该如何存储字符?认为这是一个简单的问题,也许我遗漏了什么?

最佳答案

你想要:

我。使用 fgets() 获取整行,然后

二。将行存储到 char 数组中。

char buf[0x1000];
size_t alloc_size = 4;
size_t n = 0;
char **lines = malloc(sizeof(*lines) * alloc_size);
// TODO: check for NULL

while (fgets(buf, sizeof(buf), f) != NULL) {
if (++n > alloc_size) {
alloc_size *= 2;
char **tmp = realloc(lines, sizeof(*lines) * alloc_size);
if (tmp != NULL) {
lines = tmp;
} else {
free(lines);
break; // error
}

lines[n - 1] = strdup(buf);
}
}

关于c - 读取文件并将每一行保存到 C 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16091313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com