fprintf to print text on standard output screen, why?

We can actually do this to print text on screen,

fprintf(stdout,"Hello %s\n","World");

But why?

Try to imagine that you are doing a debug log file function, which to print “debug string” to a file with specified FILE such as this

int DebugLog(FILE *fp, char *str)
{   
    if (fp==NULL)
        return -1;

    fprintf(fp,"%d : [debug] %s\n",str);
    return 1;
} 

So when you want to write the debug string to file, pass the “file output stream”, print on screen? pass “stdout”.

int main()
{
    FILE *fp=fopen("any.txt","w");
    //write to file
    DebugLog(fp,"Things failed");
    fclose(fp);
    //write to screen
    DebugLog(stdout,"Things failed");

    return 1;
}

FILE is a stream object, when you create a stream pointer, you can point to stdout. stdout is a standard output defined when you initiate main(). You can do something fun, look at another example bellow

    FILE *fp=stdout;

    stdout=fopen("out-snap","w");
    printf("Hello hello");
    fclose(stdout);

    stdout=fp;
    printf("Hello Hello Hello");

The code above redirect the standard output to a file “out-snap” and I uses fp to preserved the stdout address. Later I do fclose(stdout), I was actually closing the file stream and point back the stdout to standard output.

One thought on “fprintf to print text on standard output screen, why?

Leave a Reply

Your email address will not be published. Required fields are marked *