2

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?!

Matias
  • 23
  • 3

2 Answers2

4

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.

Achal
  • 11,629
  • 2
  • 14
  • 34
0

I don't know the details, but basically most functions that write to the console are buffered. That means when you call the function is not necessarily when the text gets printed. See: Why does printf not flush after the call unless a newline is in the format string?

serpixo
  • 310
  • 1
  • 6