Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout to file without ANSI warnings

Tags:

c

ansi-c

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?

like image 396
Darcy Rayner Avatar asked Sep 03 '25 14:09

Darcy Rayner


1 Answers

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

if (freopen("output", "w", stdin) == NULL) {
    /* error occured */
    perror("freopen");
}
like image 153
caf Avatar answered Sep 05 '25 04:09

caf