c - 如何在 C 中在终端上显示输出并同时保存到文件?

标签 c file io

这是我用于将内容打印到名为 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)

最佳答案

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

  • 使用 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输出.log 并在 C 代码中使用普通的 printf() 语句。

关于c - 如何在 C 中在终端上显示输出并同时保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52791185/

相关文章:

c - strncpy 调用的段错误

c - 使用 fseek 和 ftell 确定文件大小存在漏洞?

java 根据行号从文件中删除行

c++ - 如何将文件选择限制为单个目录?

JAVA:IO 异常:原因流关闭

c - 什么是头文件和库文件?

c - 在双向链表中的元素之后插入

python - 在 python 中编写一个新的文本文件

python - 如何终止正在运行的 iPython 进程

java - Android - 读取文本文件时内存不足