This is due to output buffering performed by the standard C library. In the first case, since you are writing on the terminal, libc buffering is line-oriented (flash is forced every time the carriage returns) to immediately display text on the screen, interactivity of performance privileges ( which should not be a problem, since terminals should not be an object for loads of text). Because of this, printf output is written immediately with some write call, which happens before the next one that you explicitly do.
In the second case, libc detects that you are writing a file, so it provides buffering to improve performance; because of this, usually the first printf will not be passed immediately, and your write will happen before libc actually flushes the buffer.
Again, this is what usually happens. I donโt think that this behavior is set by any standard ( edit:) , it is set by C99, see @Jonathan comment) (and in the second example, even with buffering enabled, the library may decide to make a flash anyway, for example, if the buffer is full your printf ).
source share