I need to read an unsigned short
using the read
system call.
According to the manpage:
read() attempts to read up to
count
bytes from file descriptorfd
into the buffer starting atbuf
.
In my case, an unsigned short
is two bytes size, so it can store the numbers up to 65535. But when I execute this code:
char buf[2];
bytes_read = read(0, buf, 2);
bytes_wrote = write(1, buf, 2);
and type in the command line, say, the number 123
, it returns only 12
. Does it not read bytes, but symbols? How can I read a value with more than 2 symbols into a 2-byte buffer? For example, the maximum values of an unsigned short
. I found nothing in either K&R or the manpages about it, so I think it's very simple.
1
, then2
, then3
; your code will read the first two of the bytes you wrote. It won't interpret (using ASCII for convenience) 0x31 followed by 0x32 as the number 12; it'll interpret it as 0x31 followed by 0x32. – Fund Monica's Lawsuit Feb 25 '17 at 21:28