【问题标题】:How to show output on terminal and save to a file at the same time in C?如何在终端上显示输出并在 C 中同时保存到文件中?
【发布时间】:2018-10-13 08:46:41
【问题描述】:

这是我用于将内容打印到名为 output.log 的文件的代码:

FILE *openFile(void)
{
    FILE *entry;
    entry = fopen("output.log", "a");
    if (entry != NULL)/*verifying whether it opened*/
    {/*printing the --- separator*/
        fprintf(entry, "---\n");/*unable to write to unopened file*/
    }
    return entry;
}

void writeFile(FILE *entry, char *category, double formerX, double 
formerY, double     latestX, double latestY)
{
    /*writing an entry to the given file, as told in the given 
    document*/
    fprintf(entry, "%4s (%7.3f, %7.3f)-(%7.3f, %7.3f) \n", category, 
    formerX, formerY, latestX, latestY);
}

/*closing the file and checking for errors*/
void closeFile(FILE *entry)
{
    if (ferror(entry))
    {
        perror("Error, can't write to the file");
    }
    fclose(entry);
}

我现在想在终端屏幕上打印相同的内容(保存在 output.log 中)。如何添加此功能?

这是 output.log 的一部分:

MOVE (  0.000,   0.000)-( 18.000,  -0.000) 
DRAW ( 18.000,  -0.000)-( 19.000,  -0.000)
DRAW ( 19.000,  -0.000)-( 20.000,  -0.000)
DRAW ( 20.000,  -0.000)-( 21.000,  -0.000)
DRAW ( 21.000,  -0.000)-( 22.000,  -0.000)
DRAW ( 22.000,  -0.000)-( 23.000,  -0.000)
DRAW ( 23.000,  -0.000)-( 25.000,  -0.000)
MOVE ( 25.000,  -0.000)-(  0.000,  -0.000)
MOVE (  0.000,  -0.000)-( -0.000,   1.000)
MOVE ( -0.000,   1.000)-( 18.000,   1.000)
DRAW ( 18.000,   1.000)-( 19.000,   1.000)

【问题讨论】:

  • 您可以先使用sprintf 将数据格式化到缓冲区中,然后通过printffprintf 输出。
  • 使用 shell 工具,您可以在另一个 shell 上使用 tail -f output.log,或者如果您的程序只打印到 stdout,您可以使用 myprog | tee output.log
  • @Gerhardh 在这种情况下,他将使用正确设置的malloc,也许snprintf
  • @Amessihel 可能的值似乎非常有限。在这里,一个固定大小的缓冲区就足够了。
  • @Amessihel 它工作正常,但我的图形搞砸了,所以我需要将 printf 输出重定向到另一个终端窗口。我怎样才能做到这一点?本质上,日志条目应该被打印到标准错误。

标签: c file io


【解决方案1】:

解决打印到终端并将输出保存到文件的方法

  • 在标准输入中使用printf(),或fprintf(stdin, "");,在fprintf();之后声明
  • 写入文件后使用system("cat output.log");(适用于linux)。
  • 使用写入后打印文件的函数


#include <stdio.h>
void printFile(FILE *fp) {
  char line[2048];
  while (fscanf(fp, "%[^\n]s", line) == 1) {
    printf("%s\n", line);
    fgetc(fp); // OR fseek(fp, 1, 1); To throw away the new line in the input
               // buffer
  }
}
int main() {
  FILE *fp;
  fp = fopen("a.txt", "r");
  if (fp == NULL) {
    printf("Error opening the file\n");
    return 1;
  }
  printFile(fp);
  return 0;
}
  • 使用linux shell
    ./a.out | tee output.log 并在 C 代码中使用普通的 printf() 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2016-07-26
    • 2018-06-06
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多