Search code examples
cfileio

How to show output on terminal and save to a file at the same time in C?


This the code I have for printing the contents to a file named 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);
}

I want to now print the same content (saved in output.log) on the terminal screen. How can I add this functionality?

Here is a section of 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)

Solution

  • Ways to solve printing to the terminal and saving output to file

    • Using printf(), or fprintf(stdin, ""); to stdin, statement after fprintf();
    • Using system("cat output.log");(works in linux) after writing to file.
    • Using function which will print the file after writing like


    #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;
    }
    
    • Using linux shell
      ./a.out | tee output.log and use normal printf() statement inside your C code.