gpt4 book ai didi

linux - 我怎样才能安全而简单地从文件或标准输入中读取一行文本?

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

鉴于 fgets 有时只包含一个换行符,而 fscanf 本质上是不安全的,我想要一个简单的替代方法来从文件中逐行读取文本。此页面是找到此类功能的好地方吗?

最佳答案

是的。以下功能应满足此要求,而不会产生任何破坏性的安全漏洞。

/* reads from [stream] into [buffer] until terminated by
* \r, \n or EOF, or [lastnullindex] is reached. Returns
* the number of characters read excluding the terminating
* character. [lastnullindex] refers to the uppermost index
* of the [buffer] array. If an error occurs or non-text
* characters (below space ' ' or above tilde '~') are
* detected, the buffer will be emptied and 0 returned.
*/
int readline(FILE *stream, char *buffer, int lastnullindex) {
if (!stream) return 0;
if (!buffer) return 0;
if (lastnullindex < 0) return 0;
int inch = EOF;
int chi = 0;
while (chi < lastnullindex) {
inch = fgetc(stream);
if (inch == EOF || inch == '\n' || inch == '\r') {
buffer[chi] = '\0';
break;
} else if (inch >= ' ' && inch <= '~') {
buffer[chi] = (char)inch;
chi++;
} else {
buffer[0] = '\0';
return 0;
}
}
if (chi < 0 || chi > lastnullindex) {
buffer[0] = '\0';
return 0;
} else {
buffer[chi] = '\0';
return chi;
}
}

关于linux - 我怎样才能安全而简单地从文件或标准输入中读取一行文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621090/

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