fgets可以读取空字符串吗?
问题描述:
假设FILE *是有效的,可以考虑:fgets可以读取空字符串吗?
char buf[128];
if(fgets(buf,sizeof buf,myFile) != NULL) {
strlen(buf) == 0; //can this ever be true ? In what cases ?
}
答
是的。除了通过1(如Ignacio所述)之外,fgets
不会对嵌入式空值做任何特殊处理。因此,如果FILE *
中的下一个字符是NUL,则strlen
将为0.这就是为什么我更喜欢POSIX getline函数的原因之一。它返回读取的字符数,因此嵌入的空值不是问题。
答
从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.
从这一点,就可以推断出的1
一个size
将导致它读取空字符串。这里的实验证实了这一点。
顺便说一句,size
的0
似乎根本不修改缓冲区,甚至没有把\0
。
+1,这似乎是正确的。 – casablanca 2010-10-13 19:44:06
如果缓冲区大小为零,则'fgets()'无法将终端写入null,是吗?它不能超出它给出的空间的末尾;如果它没有空间,它就不能写。 – 2010-10-13 19:54:52