-3

Say I have a function like

void printToSomewhere(FILE* stream, char* msg){
    fprintf(stream, "%s", msg);
}

If I want the stream to be stdout, do I have to declare that before in the calling function:

...
FILE* stdout;
printToSomewhere(stdout, "printing to stdout");
...

or can I call the function without having to define/include/etc stdout explicitly?

...
printToSomewhere(stdout, "printing to stdout");
...
galois
  • 825
  • 2
  • 11
  • 31
  • 1
    Please choose one of C and C++. – fuz Nov 12 '15 at 00:30
  • 1
    Downvoted for lack of research effort. – Baum mit Augen Nov 12 '15 at 00:34
  • @BaummitAugen I'm not sure what kind of 'research effort' should be used in a situation where one's not even quite sure how to word the question they're asking. – galois Sep 14 '16 at 03:30
  • @galois I'm referring to research effort as in looking up `stdout` in some C++ reference. Both references that turn up when searching for `stdout` in an arbitrary search engine answer this question. That's like not even a minute of work. – Baum mit Augen Sep 14 '16 at 22:13

2 Answers2

4

As with every variable, you have to declare stdout before using it. The variable stdout is declared in the header file stdio.h (or cstdio in C++). By including stdio.h (or cstdio), stdout becomes visible.

On many platforms, you can also simply declare stdout as an extern variable:

extern FILE *stdout;

although doing so is discouraged, as the C standard requires stdout to be a macro and allows it to expand to something that is not even a variable. On most plaforms however, stdio.h defines this macro simply as

#define stdout stdout

but you should refrain from making this assumption in portable software.

fuz
  • 88,405
  • 25
  • 200
  • 352
0

Yes. STDOUT is always file descriptor 1 (mandated by POSIX).

This will work:

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


void printToSomewhere(FILE* stream, const char* msg){
    fprintf(stream, "%s", msg);
}

int main()
{
    FILE* f = fdopen(1, "w+");
    printToSomewhere(f, "Hello\n");
    fclose(f);
    return 0;
}

expected output:

Hello
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Doing this might yield strange results on older Unices that use a fixed table of `FILE` pointers as the `fdopen()` call overwrites the existing `FILE` structure for file descriptor 0. Also, stdout is always file descriptor 1, not 0 and you should use the macro `STDOUT_FILENO` instead of hardcoding it. – fuz Nov 16 '15 at 08:39
  • Answer corrected, mea culpa. It's going to have to be a very old (non-posix) unix for this to be true. Surely that's a corner-case, and something unlikely to be encountered by the OP? – Richard Hodges Nov 16 '15 at 11:43
  • I'm actually not sure if it is allowed to open a file again. Let me ask. – fuz Nov 16 '15 at 12:33