fgets - 考虑空字符
fgets - Take null character into account
使用 int scanf(const char *format, ...)
, I would read one less character than the string's size, because the last character of the string has to be the null character [=14=]
.
扫描用户输入时
char str[10];
scanf("%9s", str); /* take [=10=] into account */
但是当我使用char *fgets(char *str, int n, FILE *stream)
时,我不知道应该如何指定n
。大多数网上教程都设置为sizeof(str)
,但有人告诉我应该是sizeof(str) - 1
。
那么我该如何防止缓冲区溢出呢?像这样:
char str[10];
fgets(str, 10, stdin);
或者我应该这样做:
char str[10];
fgets(str, 9, stdin);
参见 C11 7.21.7.2(强调我的):
- The
fgets
function reads at most one less than the number of characters specified by n
[...] A null character is written immediately after the last character read into the array.
- [if an error occurs] a null pointer is returned.
因此,正确的用法是使用数组的完整大小 和 检查 return 值。
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) /* all bets are off */;
使用 int scanf(const char *format, ...)
, I would read one less character than the string's size, because the last character of the string has to be the null character [=14=]
.
char str[10];
scanf("%9s", str); /* take [=10=] into account */
但是当我使用char *fgets(char *str, int n, FILE *stream)
时,我不知道应该如何指定n
。大多数网上教程都设置为sizeof(str)
,但有人告诉我应该是sizeof(str) - 1
。
那么我该如何防止缓冲区溢出呢?像这样:
char str[10];
fgets(str, 10, stdin);
或者我应该这样做:
char str[10];
fgets(str, 9, stdin);
参见 C11 7.21.7.2(强调我的):
- The
fgets
function reads at most one less than the number of characters specified byn
[...] A null character is written immediately after the last character read into the array.- [if an error occurs] a null pointer is returned.
因此,正确的用法是使用数组的完整大小 和 检查 return 值。
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) /* all bets are off */;