Search code examples
cansi-c

Redirect stdout to file without ANSI warnings


I've been trying to get a program's STDOUT redirecting to a file. So far, this code works well:

FILE *output = fopen("output","w");
if (dup2(fileno(output),1) == -1)
{
    /* An error occured. */
    exit(EXIT_FAILURE);
}

The issue is, I'm trying to stick to ANSI C, and fileno isn't ANSI. When I compile with gcc I get the warnings:

gcc -Wall -ansi -pedantic
warning: implicit declaration of function ‘fileno’

Is there any way at all to redirect STDOUT to a file in ansi C?


Solution

  • The ANSI C way to do it is freopen():

    if (freopen("output", "w", stdin) == NULL) {
        /* error occured */
        perror("freopen");
    }