C是否允许在满读垃圾的字节末尾放置字符串终止符,还是只有在读取字节为字符时才能保证字符串终止符?终止充满垃圾的字符串?
我需要从标准输入读取这样的事情,但我不知道有多少个字符阅读和EOF不保证:
Hello World!---full of garbage until 100th byte---
char *var = malloc(100 + 1);
read(0, var, 100); // read from stdin. Unfortunately, I do not know how many bytes to read and stdin is not guaranteed to hold an EOF. (I chose 100 as an educated guess.)
var[100] = '\0'; // Is it possible to place a terminator at the end if most of the read bytes are garbage ?
由于OP是使用POSIX'read'功能,我要去猜这个问题应该被标记POSIX/UNIX或类似的东西,在这种情况下,假设和字节字符(和八位字节)是相同的东西是完全有效的。顺便说一句,而不是建议一次读取一个字节(这将是非常缓慢的),你可能会建议在读取数据后进行验证。 – 2010-09-11 14:09:39