I’m writting a small code, just five lines, but it can’t runs as the correct order.
After compiling this code, It will exec "dir" first and then print my string.
But if I change it to printf ("%s\n", "asdf");, the program will run with correct order.
And I want to know why it will be this. (PS, my computer is arch with gcc 4.6.2 and I also use clang but they have the same result.)
Thank you every one.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf ("%s", "asdf");
system ("dir");
return 0;
}
The reason it looks like
diris being executed before theprintfis becauseprintfprints tostdoutandstdoutbuffers its output – your program is being executed in the correct order.stdout‘s buffer is usually flushed when (as I mentioned in this answer):'\n') is to be printedstdinfflush()is called on itThat is why adding a newline (
'\n') the string being printed causes"asdf"to be printed before the output ofdir.Other alternatives to flushing the buffer include printing to
stderr, which isn’t buffered, or usingsetbuf(stdout, NULL);to disable buffering altogether forstdout. Neither of these two approaches seem necessary for your situation, however.