1

I would like to understand why when I execute this code

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

int main()
{
    write(1, "6", 1);
    printf(" | ");
    write(1, "6", 1);
}

I get this output

66 | %

Instead of

6 | 6%

even with sleep before and after the printf it doesn't fix it. Thanks

MegaIng
  • 7,361
  • 1
  • 22
  • 35
Maxou
  • 37
  • 5
  • 2
    See [Accepted Answer - What do fully buffered, line buffered and unbuffered mean in C?](https://stackoverflow.com/a/36573578/3422102) What happens if you add `fflush (stdout);` after each command??? Or `fflush (stdout);` after the first two commands and change the last to `write(1, "6\n", 2);` – David C. Rankin Apr 20 '22 at 03:28
  • It works with the fflush(stdout); thanks you, so if I understand the link you gave me, the write function write instantly to stdout and printf wait a newline or to fill his buffer before printing it to stdout ?!? – Maxou Apr 20 '22 at 03:40
  • 1
    Yes. `printf()` is *line-buffered* so it doesn't print anything until a `'\n'` is encountered (or the underlying buffer is filled -- it's large). So you use `fflush()` to force all the buffered characters to be written. `fflush()` is only needed after `printf()` because `write` will write the `'6'` to stdout. `printf()` will buffer `" | "`, the final `write()` will write another `'6'` before program exit (which flushes all streams). So placing `fflush()` after `printf()` keeps the output in the order written. – David C. Rankin Apr 20 '22 at 04:49
  • Detail, `stdout` is _usually_ line-buffered. – chux - Reinstate Monica Apr 20 '22 at 06:06
  • Thanks u a lot my friend that make more sense ;) – Maxou Apr 20 '22 at 06:07

1 Answers1

2

Try fflush(stdout); The file I/O is buffered to improve performance. Fflush writes the buffers out. Mixing the 2 may still give you surprises, so I would not recommend doing it.

Sami Sallinen
  • 3,203
  • 12
  • 16