Redirect stdout to file without ANSI warnings

馋奶兔 提交于 2019-12-02 05:57:14

问题


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");
}


来源:https://stackoverflow.com/questions/7252254/redirect-stdout-to-file-without-ansi-warnings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!