tags:

views:

86

answers:

2

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 bytes 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 ?
+1  A: 

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...

esalaka
Since OP is using the POSIX `read` function, I'm going to guess this question should be tagged posix/unix or something like that, in which case the assumption that bytes and chars (and octets) are the same thing is perfectly valid. BTW instead of suggesting reading a byte at a time (which would be extremely slow), you might instead suggest validating the data after reading it.
R..
+8  A: 

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 */
Federico Ramponi