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
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;
}
CodePudding user response:
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".