amin__
amin__

Reputation: 1058

confusing console and file output when using system() function

I have the following code,

#include<stdio.h>
#include<stdlib.h>

int main()
{
    //freopen("file1","w",stdout);
    char str[]="command line with file";
    char s[]="extra string";
    puts(str);
    puts(s);
    system("PAUSE");    
    return 0;
}

when I see the output on console it shows me,

command line with file
extra string
Press any key to continue . . . 

And I expect same output when writing output into a file by removing the commented line in code. But it outputs like,

Press any key to continue . . . 
command line with file
extra string

why this distinction between file and console output??? here system("PAUSE") function is responsible for the string output Press any key to continue . . .

Upvotes: 1

Views: 98

Answers (1)

Alan Curry
Alan Curry

Reputation: 14711

When writing to a terminal, stdout is line-buffered. It writes each line immediately. When writing to a file, it's block-buffered. It stores a few kilobytes in a buffer and flushes them out when you call fflush, or when the buffer is full, or when the program ends. The pause message is being written by a separate process which exits before your original process, at which point it must flush its buffer (if it has one). Then your original process's system() ends and it reaches the end of main() and exits, flushing the buffer containing your two test strings.

Upvotes: 6

Related Questions