Redirect stdout to file without ANSI warnings

2019-02-26 20:13发布

问题:

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?

回答1:

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

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


标签: c ansi