Home > Blockchain >  Write the output of a function having many printf() statement in a text file
Write the output of a function having many printf() statement in a text file

Time:02-05

I have a function which writes a matrix using the printf() function. Is there a way to capture all the output of the matrix_output() function without having to each time re-open the file and append new content so that at the end, the content of file.txt is the following:

0   1   2   
1   2   3   
2   3   4   

Here is the code:

/* main.c */
#include <stdio.h>
#include <stdlib.h>

void matrix_output();

void matrix_output() {
  FILE *fp;
  fp = fopen("file.txt", "w");
  fclose(fp);
  for (int i = 0; i < 3; i  ) {
    for (int j = 0; j < 3; j  ) {
      FILE *fp;
      fp = fopen("file.txt", "ab");
      fprintf(fp, "%d\t", i j);
      fclose(fp);
    }
    FILE *fp;
    fp = fopen("file.txt", "ab");
    fprintf(fp, "\n");
    fclose(fp);
  }
}

int main() {
  matrix_output();

  return 0;
}

CodePudding user response:

Indeed, as pointed out in the comment, I actually don't need to open and close the file each time:

/* main.c */
#include <stdio.h>
#include <stdlib.h>

void matrix_output(void);

void matrix_output(void) {
    FILE *fp;
    fp = fopen("file.txt", "w");
    for (int i = 0; i < 3; i  ) {
        for (int j = 0; j < 3; j  ) {
            fprintf(fp, "%d\t", i   j);
        }
        fprintf(fp, "\n");
    }
    fclose(fp);
}

int main() {
    matrix_output();
    return 0;
}

CodePudding user response:

Re:

Is there a way to capture all the output of the matrix_output() function without having to each time re-open the file and append new content at the end?

Yes, by not closing the file. The write operation starts at the current file offset. After a successful write, the file's offset is updated by the number of bytes actually written.

So if you write 10 bytes to a file, the file's offset is updated by 10 bytes (assuming a successful write operation), and a subsequent write would start at that updated file offset.

  • Related