vrillon99
vrillon99

Reputation: 35

I can't understand this result

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

int main(void)
{
   printf("%d\t", 1);
   write(1, "Acorn\n", 6);
   printf("%d\t", 2);
   write(1, "Book\n", 5);

   return 0;
}

I want to get the result below.

1   Acorn

2   Book

But above code's result is below.

Acorn

Book

1        2

I can't solve this problem. I thought hard about this.

What should I do to make the code which can print first result?

Upvotes: 0

Views: 44

Answers (2)

stdio is buffered. You need to call fflush(3) before each call to write(1, ... (since it is a syscall), or else end each printf format string with a \n (since stdout is generally line-buffered).

BTW, you could fill a string buffer using snprintf(3) then later write(2) it. See also fdopen(3) & dprintf(3) & setvbuf(3) & asprintf(3) ...

Upvotes: 2

blast_hardcheese
blast_hardcheese

Reputation: 454

The output of printf is stuck in the output buffer. In order to interoperate with write, you'll need to flush:

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

int main(void)
{
   printf("%d\t", 1);
   fflush(stdout);
   write(1, "Acorn\n", 6);
   printf("%d\t", 2);
   fflush(stdout);
   write(1, "Book\n", 5);

   return 0;
}

Upvotes: 1

Related Questions