这是来自 chux 对这里问题的回答:How to get the strings from a file and store in a 2D char array and compare that 2D char array with a string in C?
Lop off the potential tailing '\n'
size_t len = strlen(buf); if (len && buf[len-1] == '\n') buf[--len] = '\0';
我理解 if 语句的第二部分(检查 if buf[len-1] == '\n'),但不要以为我理解其中的 if (len) 部分...它只是检查缓冲区中的任何内容是否实际上有一个非零长度(如果是这样,怎么会出现 strlen 返回 0 的情况?)还是别的什么?
最佳答案
while (i < 100 && fgets(buf, sizeof buf, f) != NULL ) {
// Lop off the potential tailing '\n'
size_t len = strlen(buf);
if (len && buf[len-1] == '\n') buf[--len] = '\0';
Is it simply checking if there's actually a non-zero length to whatever's in the buffer
是的。
代码在尝试 buf[len-1]
之前测试 len != 0
以防止访问超出范围的 buf[]
。< br/>
@Jonathan Leffler
(and if so, how can a situation where strlen returns 0 arise?)
防御性编码:读取的行可能以空字符开头。
前面的代码有 fgets(buf, sizeof buf, f)
,它读取一个行,然后形成一个字符串。在 C 标准库1 中,输入的行 是'\n'
之前的字符。 null character 对输入没有特殊意义,它就像其他字符一样。在 line 使用 fgets()
读取并保存在 buf[]
后,将附加一个 null 字符。 size_t len = strlen(buf);
返回基于第一个空字符的长度,不一定是附加的字符。
如果文本文件行是
'\0', 'a', 'b', 'c', '\n'
然后 fgets(buf, ...)
将导致 buf[]
为
'\0', 'a', 'b', 'c', '\n', '\0'
并且len == 0
。
ASCII 文本文件很少包含空字符。他们的存在通常是错误的或恶意的(黑客利用)。 空字符 在 UTF-16 文本文件中很常见,但读取带有相关代码的此类文件也有其他问题。
1 "文本流是由行组成的有序字符序列,每行由零个或多个字符加上一个终止换行符组成。无论是最后一行需要一个终止换行符是实现定义的。” C11dr §7.21.2 2
关于c - 以下代码中 if(len ....) 的含义/逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52962064/