1

my code is :

#include <stdio.h>
void main( int argc, char** argv) {
    printf("%s", argv[0]);
    system("pwd");
}

The output is:

[river@localhost studio]$ ./a.out 
/home/river/Desktop/studio
./a.out[river@localhost studio]$

It seems that system("pwd") print first , then print argv[0] . why? If I add a statement like following :

#include <stdio.h>

    void main( int argc, char** argv) {
        printf("%s", argv[0]);
        fflush(stdout);
        system("pwd");
    }

The output is :

[river@localhost studio]$ ./a.out 
./a.out/home/river/Desktop/studio

It work normally, why ?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
river
  • 694
  • 6
  • 22

2 Answers2

2

The printf call only puts the output in a buffer. For the buffer to actually be written it needs to be flushed. Output is automatically flushed when you print a newline, so if you replace the format-string in printf with this: "%s\n" it should work without the call to fflush.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    ... and calling "system" does not flush the output stream or even use the output stream - the command invoked by "system" writes directly and immediately to the console, then the buffer is flushed when the program ends, and the line you printfed is shown. – James McLeod Oct 31 '11 at 09:52
1

The other way to 'fix' it:

printf("%s\n", argv[0]);

The thing is that stdout is linebuffered by default.

See:

sehe
  • 374,641
  • 47
  • 450
  • 633