gpt4 book ai didi

c - 在没有预定义缓冲区的情况下使用 fgets()

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:23 24 4
gpt4 key购买 nike

我需要再问一个关于从标准输入读取的问题。我正在从 stdin 读取一大串行,但绝对不知道每行的大小是多少。所以我不想像 50Mio 这样的缓冲区只用于具有三个字符行的文件,而不是每行使用这些 50 Mio 的文件。所以目前我有这段代码:

int cur_max = 2047;
char *str = malloc(sizeof(char) * cur_max);
int length = 0;

while(fgets(str, sizeof(str), stdin) != NULL) {
//do something with str
//for example printing
printf("%s",str);
}

free(str);

因此,我对每一行都使用了 fgets,并且每行的第一个大小确实为 2047 个字符。我的计划是在一行达到限制时增加缓冲区 (str) 的大小。所以我的想法是用长度来计算大小,如果当前长度大于 cur_max,那么我将 cur_max 加倍。思路出自这里Read line from file without knowing the line length我目前不确定如何使用 fgets 执行此操作,因为我认为 fgets 不是一个字符一个字符地执行此操作,所以我不知道何时增加大小。

最佳答案

代码不正确

sizeof(str)是指针的大小,例如 2、4 或 8 个字节。传递给 fgets() str指向的内存大小. @Andrew Henle @Steve Summit

char *str = malloc(sizeof(char) * cur_max);
...
// while(fgets(str, sizeof(str), stdin) != NULL
while(fgets(str, cur_max, stdin) != NULL

环境限制

文本文件fgets()不是阅读超长行的可移植解决方案。

An implementation shall support text files with lines containing at least 254 characters, including the terminating new-line character. The value of the macro BUFSIZ shall be at least 256 C11 §7.21.2 9

所以一旦行长超过BUFSIZ - 2 ,关于 C 标准库函数是否可以处理文本文件的代码是独立的。

因此,要么以二进制形式读取数据,要么使用其他可确保所需功能的库,要么全靠希望。

备注:BUFSIZ<stdio.h> 中定义

关于c - 在没有预定义缓冲区的情况下使用 fgets(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51059508/

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