【问题标题】:Piping terminal output to file from within C program从 C 程序中将终端输出管道传输到文件
【发布时间】:2015-07-22 06:26:01
【问题描述】:

我希望将输出到标准输出的所有内容也保存在我的 C 代码中的文件中。我知道我可以通过在命令行上调用进程并将其通过管道传输到文件来做到这一点:

 myprogram.exe 1>logfile.txt

例如。但我想知道是否有办法从 C 代码本身中做到这一点。 printf() 家族中是否有一个函数可以同时输出到终端和具有相同参数的指定文件?

如果不是,编写我自己的 printf() 风格的函数需要什么语法,在其中调用 printf() 和 fprintf(),使用与 printf() 相同的参数风格?

【问题讨论】:

  • 阅读variadic functions。然后阅读vprintf and vfprintf
  • @JoachimPileborg,这是一个 C++ 解决方案。 OP 的问题被标记为 C。
  • 看看the source code for tee。这可能会给你一些工作。
  • @RSahu 没关系,可变参数函数是一样的,在 C 中也是一样的。
  • 感谢您的建议。我原则上熟悉可变参数函数,但从未使用过它们,所以我必须尝试一下。

标签: c file-io printf output


【解决方案1】:

您可以使用 fprintf() 函数,它的工作方式与 printf() 非常相似。

这是一个例子:

FILE *fp;
int var = 5;
fp = fopen("file_name.txt", "w");// "w" means that we are going to write on this file
fprintf(fp, "Writting to the file. This is an int variable: %d", var);

你的文件的输出是这样的:

This is being written in the file. This is an int variable: 5

注意:使用 w 作为参数打开文件会在每次打开文件时破坏文件的内容。

要写入文件,您必须使用文件操作命令,不能使用 printf 写入文件(它只打印到标准输出)。你可以使用:

sprintf(buf,"%d",var);  //for storing in the buffer
printf(buf);       //output to stdout
fputs(buf, fp);   //output to file

【讨论】:

  • 不是我想要的。我知道如何使用 printf() 系列函数,我希望的是一个打印函数,它可以同时输出到两个不同的流,例如 stdout 和我指定的 FILE 指针。
  • 我已经编辑了我的答案看看,我希望你得到你的答案。
【解决方案2】:

放弃使用可变参数函数的建议:

#include <stdio.h>
#include <stdarg.h>

/*
 * Not all compilers provide va_copy(), but __va_copy() is a
 * relatively common pre-C99 extension.
 */
#ifndef va_copy
#ifdef __va_copy
#define va_copy(dst, src) __va_copy((dst), (src))
#endif
#endif

#ifdef va_copy
#define HAVE_VACOPY 1
#endif

int
ftee(FILE *outfile, const char *format, ...)
{
    int result;
    va_list ap;
#if HAVE_VACOPY
    va_list ap_copy;
#endif

    va_start(ap, format);

#if HAVE_VACOPY
    va_copy(ap_copy, ap);
    result = vfprintf(outfile, format, ap_copy);
    va_end(ap_copy);
    if (result >= 0)
        result = vprintf(format, ap);
#else
    result = vfprintf(outfile, format, ap);
    if (result >= 0) {
        va_end(ap);
        va_start(ap, outfile);
        result = vprintf(format, ap);
    }
#endif
    va_end(ap);
    return result;
}

它可以像标准的fprintf 函数一样使用,你可以指定一个输出文件,除了它还将正常输出写入stdout。我试图支持相对较新的编译器,它们仍然没有 va_copy() 宏(在 C99 中定义),例如 Visual Studio 2012 附带的编译器(VS2013 终于有了)。一些 C 运行时还会有条件地定义 va_copy(),这样在启用严格 C89/C90 模式的情况下编译将使其未定义,而 __va_copy() 可能保持定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    相关资源
    最近更新 更多