fgets可以读取空字符串吗?

时间:2010-10-13 19:33:38

标签: c

假设FILE *有效,请考虑:

char buf[128];

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

2 个答案:

答案 0 :(得分:4)

来自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.

由此可以推断size 1会导致它读取空字符串。这里的实验证实了这一点。

顺便提一下,size 0似乎根本没有修改缓冲区,甚至没有放入\0

答案 1 :(得分:4)

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