C是否允许在读取字节的末尾放置一个字符串终止符,或者仅在读取的字节是字符时才能保证?
我需要从stdin读取类似的东西,但我不知道要读取多少个字符并且不能保证EOF:
Hello World!---full of garbage until 100th byte---
Run Code Online (Sandbox Code Playgroud)
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 ?
Run Code Online (Sandbox Code Playgroud)
read()
返回实际读入缓冲区的字符数(如果出错,则返回<0).因此以下应该有效:
int n;
char *var = malloc(100 + 1);
n = read(0, var, 100);
if(n >= 0)
var[n] = '\0';
else
/* error */
Run Code Online (Sandbox Code Playgroud)