Search code examples
cprintfsequential

why write() executes before printf()? Is not it supposedly sequential?


this is the code:

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

void main(){
    char str1[18]= "moo\0 cuek\n";
    printf("lel: %s",str1);

    write(STDOUT_FILENO,str1,18);
    write(STDOUT_FILENO,"meow ",19);

}

and the output is:

moo cuek
meow moo cuek
lel:moo

also, why is meow printed first and then moo cuek (second line)

P.S. when I put \n inside printf like:

printf("lel: %s \n",str1);

I get:

lel:moo
moo cuek
meow moo cuek

Why?!


Solution

  • Here

    printf("lel: %s",str1);
    

    printf() prints the data on file stream where its points and default it is stdout stream and stdout stream is line buffered i.e you need to flush the buffer by calling fflush(stdout)or adding \n char. For e.g

    printf("lel: %s",str1);
    fflush(stdout);
    

    or

    printf("lel: %s\n",str1); /* newline char has another use apart from giving newline i.e clear the buffer */
    

    Or you can disable the buffering by calling setbuf().

    while here

     write(STDOUT_FILENO,str1,18);
    

    write() is a system call which is not buffered IO i.e it doesn't buffer the data, hence it immediately write the data into STDOUT_FILENO.