BodneyC BodneyC - 14 days ago 4
C Question

C, Call to function twice, one writes to file, one writes to terminal

fairly new to C and have a slight issue,

I have a function which is filled with 'fprintf' statements and some calculations relevant to the output.
When I call it from main() it works correctly and prints to the document, I then want to call it a second time and have the same text but only outputted to the terminal (as in printf).

I have a flag in the function parameters which would specify this choice but no way of accomplishing it aside from an if statement for every fprintf saying:

if (flag == 1)
{
fprintf(pt, "Random text...
} else {
printf("The same random text...
}


Which seems dreadfully inefficient. My other idea was to (with my little understanding of it) use #define within the function in the context:

if (flag== 1)
{
#define fprintf(pt, printf(
}


Which not only seemed very cheap but did not work.

Any ideas would be appreciated,
Thanks

Answer

How about something like this:

FILE *out=stdout;

fprintf(out,"Hello World\n");

Since this is a function, you can pass in the out pointer as an argument. When printing to the terminal, just assign stdout to it.