I was trying to Implement my own printf function and I discovered this strange behavior, when you try to print something using printf()
and after it you try to print something else using write()
, the output of write()
is printed before the output of printf()
!
As you can see in the example below :
#include <stdio.h>
#include <unistd.h>
int main()
{
printf(" hello world ");
write(1, "what am doing here", 18);
return (0);
}
and this is the output of the above code :
"what am doing here hello world "
#edit
After I read the answer on the other question I found that
printf is buffered and write is not.
For output to a terminal, the C stdio system has a feature that it flushes the buffers whenever it sees a newline '\n'. For more about stdio buffering look at the documentation for setvbuf.a
but in my case there is no new line '\n'
in printf()
so that's why the output of write()
precedes the output of printf()
.
for example if you use the same code above but with adding \n
to printf()
the output will change and the output of printf will be the first.
#include <stdio.h>
#include <unistd.h>
int main()
{
printf(" hello world\n"); //adding \n
write(1, "what am doing here", 18);
return (0);
}
the output this time is different :
" hello world what am doing here"
hint : this output from online compilers but with the terminal that I'm using, it's output doesn't change and the output of write()
still printed before the output of printf()
correct me if I am wrong.