Igor Liferenko Igor Liferenko - 1 month ago 7
C Question

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

The following code demonstrates that if there is

\0
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
a
.

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

Answer

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);
Comments