fgets()总是使用\ 0终止char缓冲区吗?

Ree*_*Ree 17 c fgets

即使已经达到EOF,fgets()总是使用\ 0终止char缓冲区吗?它看起来确实如此(它肯定在ANSI K&R书中提供的实现中),但我想我会要求确定.

我想这个问题适用于其他类似的函数,比如gets().

编辑:我知道在"正常"情况下附加\ 0,我的问题是针对EOF或错误条件.例如:

FILE *fp;
char b[128];
/* ... */
if (feof(fp)) {
    /* is \0 appended after EACH of these calls? */
    fgets(b, 128, fp);
    fgets(b, 128, fp);
    fgets(b, 128, fp);
}
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 11

fgets确实总是向读缓冲区添加'\ 0',因此它会size - 1从流中读取大多数字符(size作为第二个参数).

永远不要使用,gets因为你永远不能保证它不会溢出你给它的任何缓冲区,所以虽然它在技术上总是终止读取字符串这实际上没有帮助.


pmg*_*pmg 7

永远不要用得!!

    7.19.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.
    Returns
3   The fgets function returns s if successful. If end-of-file is encountered
    and no characters have been read into the array, the contents of the array
    remain unchanged and a null pointer is returned. If a read error occurs
    during the operation, the array contents are indeterminate and a null
    pointer is returned.

所以,是的,当fgets()不返回NULL时,目标数组始终具有空字符.

如果fgets()返回NULL,则目标数组可能已更改,并且可能没有空字符.从NULL获取NULL后再也不依赖于数组fgets().


编辑示例已添加

$ cat fgets_error.c
#include <stdio.h>

void print_buf(char *buf, size_t len) {
  int k;
  printf("%02X", buf[0]);
  for (k=1; k<len; k++) printf(" %02X", buf[k]);
}

int main(void) {
  char buf[3] = {1, 1, 1};
  char *r;

  printf("Enter CTRL+D: ");
  fflush(stdout);
  r = fgets(buf, sizeof buf, stdin);
  printf("\nfgets returned %p, buf has [", (void*)r);
  print_buf(buf, sizeof buf);
  printf("]\n");

  return 0;
}
$ ./a.out
Enter CTRL+D:
fgets returned (nil), buf has [01 01 01]
$

看到?没有NUL在buf :)