Igor Liferenko Igor Liferenko - 1 year ago 54
C Question

Why '\0' ends the input of read()?

The following code demonstrates that if there is

in the input, the input is not read after it.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
int fd;
int fd2;
char buf[200];
int n;
char fname[] = "/tmp/tst-perror.XXXXXX";
fd = mkstemp (fname);
fd2 = dup (fd);
write(fd2, "a", 2); // \0 is written out
write(fd2, "b", 1);
write(fd2, "\n", 1);
close (fd2);
lseek (fd, 0, SEEK_SET);
n = read (fd, buf, sizeof (buf));
printf("%.*s", (int) n, buf);
close (fd);
unlink (fname);
return 0;

The output is

If we use
instead of
in the first
, the output is
. Is it proper behavior? I did not find anything about it in read(2).

Answer Source

The input is read after the \0 byte. However, %s printf format specifier expects a \0-terminated string.

Instead of printf try writeing n bytes to STDOUT_FILENO or 1:

write(1, buf, n);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download