R Sahu
R Sahu

Reputation: 206567

Is stdout required to be a text stream?

I ran the following program under cygwin/gcc 4.7.3 and VS 2010.

#include <stdio.h>

int main()
{
   printf("This is a test.\n");
   return 0;
}

The output of running the program under those environments showed that VS 2010 treats stdout as a text stream.

Questions:

  1. Is stdout required to be a text stream?
  2. Is an implementation free to choose whether it uses a text stream or a binary stream for stdout?

EDIT

The question of how to write to stdout in binary mode is different from whether stdout is required to be a text stream or a binary stream.

Upvotes: 2

Views: 634

Answers (3)

Wintermute
Wintermute

Reputation: 44023

stdout is required to be a text stream, as are stdin and stderr. From the C99 standard, 7.19.3 (7):

At program startup, three text streams are predefined and need not be opened explicitly -- standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). (...)

(Emphasis mine)1

For reference: in the 2011 revision of the C standard, this has been moved unchanged to 7.21.3 (7).2

Note that this means that these three streams are text streams at startup. Some platforms provide ways to switch the mode later, such as _setmode under Windows.

1 Just for the sake of completeness: that stdin, stdout, and stderr refer to these streams is defined in 7.19.1 (3).
2 The section mentioned in footnote 1 is moved to 7.21.1 (3) in C11.

Upvotes: 4

abhi-rao
abhi-rao

Reputation: 2785

stdout is not required to be a text stream - as in the case of redirection.

So I guess the answer is 'yes' to your second question.

Check this out - What is the simplest way to write to stdout in binary mode?

Upvotes: 2

Alex Reynolds
Alex Reynolds

Reputation: 96937

You can stream raw bytes to stdout using fwrite() — or write(), with the equivalent file descriptor for stdout. This is how compression tools work, for instance.

Upvotes: 0

Related Questions