开发者

Terminate string full of garbage?

开发者 https://www.devze.com 2023-01-15 23:44 出处:网络
Does C allow to place a string terminator at the end of read bytes full of garbage or is it only guaranteed if the read 开发者_如何学Gobytes are chars ?

Does C allow to place a string terminator at the end of read bytes full of garbage or is it only guaranteed if the read 开发者_如何学Gobytes are chars ?

I need to read something like this from stdin but I do not know how many chars to read and EOF is not guaranteed:

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 ?


read() returns the number of characters that were actually read into the buffer (or <0 in the case of an error). Hence the following should work:

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


It is possible to place a terminator at the end, but the end result might be Hello World! and a long string of garbage after that.

Bytes are always chars. If you wanted to accept only printable characters (which the garbage at the end might contain, anyway) you could read the input one character at a time and check if each byte's value is between 0x20 and 0x7E.

Although that's only guaranteed to work with ASCII strings...

0

精彩评论

暂无评论...
验证码 换一张
取 消