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()
无法写入终端空值,是吗?它不能写超过给定空间的尽头;如果没有空间,它就不能写。