1. 程式人生 > >Results of printf() and system() are in the wrong order when output is redirected to a file

Results of printf() and system() are in the wrong order when output is redirected to a file

I have a C program that compiles to an executable called myprogram. This is its main function:

int main(int argc, char ** argv) {
  printf("this is a test message.\n");
  system("ls");

  return 0;
}

When I run myprogram > output.txt in a Linux shell and then examine output.txt, I see the output of ls

listed above "this is a test message."

I feel like it should be the other way around. Why is this happening, and what can I do so that "this is a test message" appears at the top of output.txt?

If it matters, I'm new to both C and working in a command line.