终止充满垃圾的字符串?

时间:2010-09-11 11:48:25

标签: c

C是否允许在读取字节的末尾放置一个字符串终结符,或者仅在读取的字节是字符时才能保证?

我需要从stdin读取类似的东西,但我不知道要读取多少个字符并且不能保证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 ?

2 个答案:

答案 0 :(得分:8)

read()返回实际读入缓冲区的字符数(或者在出错时为< 0)。因此,以下应该有效:

int n;
char *var = malloc(100 + 1);
n = read(0, var, 100);
if(n >= 0)
   var[n] = '\0';
else
   /* error */

答案 1 :(得分:1)

可以在末尾放置终结符,但最终结果可能是Hello World!之后还有一长串垃圾。

字节始终是字符。如果您只想接受可打印字符(最后可能包含垃圾),您可以一次读取输入的一个字符,并检查每个字节的值是否在0x200x7E之间。

虽然只能保证使用ASCII字符串......