Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C FGET是否可以读取空字符串?_C - Fatal编程技术网

C FGET是否可以读取空字符串?

C FGET是否可以读取空字符串?,c,C,假设文件*有效,请考虑: char buf[128]; if(fgets(buf,sizeof buf,myFile) != NULL) { strlen(buf) == 0; //can this ever be true ? In what cases ? } 从fgets(3)手册页: 描述 fgets() reads in at most one less than size characters from stream and stores them into

假设文件*有效,请考虑:

char buf[128];

if(fgets(buf,sizeof buf,myFile) != NULL) {
   strlen(buf) == 0; //can this ever be true ? In what cases ?
}
fgets(3)
手册页:

描述

  fgets() reads in at most one less than size characters from stream  and
  stores  them  into  the buffer pointed to by s.  Reading stops after an
  EOF or a newline.  If a newline is read, it is stored into the  buffer.
  A '\0' is stored after the last character in the buffer.

  gets() and fgets() return s on success, and NULL on error or  when end
  of file occurs while no characters have been read.
返回值

  gets() and fgets() return s on success, and NULL on error or  when end
  of file occurs while no characters have been read.
由此可以推断
size
1
将导致它读取空字符串。这里的实验证实了这一点


顺便说一句,大小为
0
size
似乎根本不会修改缓冲区,甚至没有输入
\0

是。除了传递1(如Ignacio所述),
fgets
不会对嵌入的空值进行任何特殊处理。因此,如果
文件*
中的下一个字符是NUL,
strlen
将是0。这就是我喜欢POSIX函数的原因之一。它返回读取的字符数,因此嵌入的空值不是问题。

如果缓冲区大小为零,则
fgets()
无法写入终端空值,是吗?它不能写超过给定空间的尽头;如果没有空间,它就不能写。