Question
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 ?
Solution
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
.
OTHER TIPS
The other way to 'fix' it:
printf("%s\n", argv[0]);
The thing is that stdout is linebuffered by default.
See:
- setbuf(), setvbuf()
- stdbuf
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow