Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stream the output of a void function using printf()

I want to store the output of a function (matrix_output_printf()) printing the following output (a matrix):

0   1   2   
1   2   3   
2   3   4   

I would like to save this output in a text file.

In a first attempt, I modified the original in matrix_output_fprintf() so that it stores the output continuously using fprintf(). I indeed stores the output but the code of matrix_output_printf() has been changed

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, I would like not to modify matrix_output_printf() as, let’s say, it is part of a package and want to test it without modifiying it.
Is there a way to store (using C and not bash) the output of matrix_output_printf() from outside the function (or without using fprintf()?

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_printf(){
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      printf("%d\t", i+j);
    }
    printf("\n");
  }
}

void matrix_output_fprintf(){
  FILE * fp;
  fp = fopen("file.txt", "w");
  fclose(fp);
  fp = fopen("file.txt", "ab");
  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_printf();
  matrix_output_fprintf();
  return 0;
}

EDIT

The complete working code for me was:

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

void matrix_output();

void matrix_output_printf(){
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      printf("%d\t", i+j);
    }
    printf("\n");
  }
}

int main ()
{ 
  freopen("file.txt", "wb", stdout);
  matrix_output_printf();
  return 0;
}

>Solution :

If you want to redirect stdout to a file, you can do that with the freopen function:

freopen("file.txt", "wb", stdout);

After this call, any write to stdout will write to the file "file.txt".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading