Linux C修改printf()输出到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10947335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:43:48  来源:igfitidea点击:

C modifying printf () to output to a file

clinuxunixprintf

提问by user1317277

Is there a way to modify the printfin order to output string on a file rather than to the console?

有没有办法修改printf以将字符串输出到文件而不是控制台?

I tried looking up something on the Internet and found calls like dup, dup2and fflushthat might be associated with this.

我试着找了互联网和电话找到喜欢的东西dupdup2fflush可能与此有关。

EDIT:

编辑:

Maybe I wasn't clear.. the thing is that this was in a C exam question.. the question is as follows:

也许我不清楚..问题是这是在C考试问题中..问题如下:

Explain how a program that normally output strings to screen (using printf()) can be made to output string to a file, withoutchanging any code in the mentioned program.

解释如何使通常将字符串输出到屏幕(使用printf())的程序可以将字符串输出到文件,而无需更改上述程序中的任何代码。

采纳答案by ott--

This is usually done with I/O-redirection (... >file).

这通常通过 I/O 重定向 (... >file) 完成。

Check this little program:

检查这个小程序:

#include <stdio.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
    if (isatty (fileno (stdout)))
        fprintf (stderr, "output goes to terminal\n");
    else
        fprintf (stderr, "output goes to file\n");

    return 0;
}

ottj@NBL3-AEY55:~ $ ./x
output goes to terminal
ottj@NBL3-AEY55:~ $ ./x >yy
output goes to file

回答by user1202136

Use either sprintfto write to a string, then to a file, or fprintfdirectly.

使用要么sprintf写入字符串,然后写入文件,要么fprintf直接写入。

http://linux.die.net/man/3/fprintf

http://linux.die.net/man/3/fprintf

回答by dasblinkenlight

If you do not have liberty to modify the source code that does printing, you can use freopenon stdoutto redirect to a file:

如果您没有自由修改进行打印的源代码,您可以使用freopenonstdout重定向到一个文件:

stdout = freopen("my_log.txt", "w", stdout);

This borders on a hack, however, because command-line redirects will stop working as expected. If you do have access to the code that does printing, using fprintfis preferred.

然而,这接近于黑客攻击,因为命令行重定向将停止按预期工作。如果您确实可以访问进行打印的代码,fprintf则首选使用。

You can also switch your stdouttemporarily for a function call, and then put it back:

你也可以stdout暂时切换你的函数调用,然后把它放回去:

FILE *saved = stdout;
stdout = fopen("log.txt", "a");
call_function_that_prints_to_stdout();
fclose(stdout);
stdout = saved;

回答by glglgl

The other answers don't cope with the problem of not changing any code.

其他答案无法解决不更改任何代码的问题。

So, depending on the environment, the only thing that is left is stdout redirection when calling the program.

因此,根据环境,唯一剩下的就是调用程序时的 stdout 重定向。

./program > target_file

回答by MarkB

The lecturer was consulted and this was the correct solution provided (by the lecturer himself):

咨询了讲师,这是提供的正确解决方案(由讲师本人提供):

int main {
    int newFile = open(desiredFilePath, O_WRONLY)
    if ((fork())==0) {
        dup2(newFile,stdout) // Explained below
        close newFile
        Set stdout as CLOSE_ON_EXEC false
        exec the user program
    }
    else{
        Wait for child
    }
    return 0
}

The logic behind dup2: here stdout is set as a copy of newFile, meaning that FD 0 is now actually the user required file and not the console. This is because the default behavior of dup 2 is to close the second parameter's filedescriptor and assign it to the first parameter.

dup2 背后的逻辑:这里 stdout 被设置为 newFile 的副本,这意味着 FD 0 现在实际上是用户需要的文件而不是控制台。这是因为 dup 2 的默认行为是关闭第二个参数的文件描述符并将其分配给第一个参数。