c - fgets 应该使用什么大小?

标签 c string styles fgets code-readability

我的一个程序中有以下代码段:

char input[LINE_SIZE + 1]; /* +1 for '\0'. */

while(fgets(input, LINE_SIZE, stdin) != NULL)
{
    /* Do stuff. */
}

在一个已被删除的问题中,有人向我指出我的代码可能存在错误。我用“+ 1”表示法声明字符串,以使代码更具信息性和可读性(确保我不会忘记考虑 NULL 终止符,因为这曾经是一个问题)。但是,有人告诉我,fgets 的第二个参数应该使用完全相同的大小。我在这里看到其他帖子和我做同样的做法。

我不确定。在 fgets 参数中也不包含“+ 1”是否是一种不好的做法?

最佳答案

7.21.7.2 The fgets function

Synopsis

1        #include <stdio.h>
         char *fgets(char * restrict s, int n, FILE * restrict stream);

Description

2     The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

C 2011 Online Draft

添加了强调。

如果指定 LINE_SIZE , 然后 fgets将读取最多 LINE_SIZE - 1字符转化为input , 并将在最后一个输入字符后写入一个 0 终止符。注意 fgets如果有空间,将存储换行符。

关于c - fgets 应该使用什么大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42404627/

相关文章:

c# - 如何将字符串转换为 base64 字节数组,这有效吗?

javascript - Objective C 组件通过字符串分隔

java - 用一个 <br> 替换所有连续的 "\r\n or\n"

c++ - 此代码似乎在分配范围之外附加字符

为 OpenGL 使用正确计算模型和 View 矩阵?

android - 如何从 drawable 引用到 style

css - 内部样式表不覆盖外部样式表?

wpf - 在样式的名称范围中找不到 Storyboard

将文本文件内容复制到 C 中的二维数组中

c - Linux下动态加载库的地址范围