The screen print is confusing ?

124 views Asked by At

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 ?

2

There are 2 answers

1
Some programmer dude On BEST ANSWER

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.

0
sehe On

The other way to 'fix' it:

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

The thing is that stdout is linebuffered by default.

See: