BodneyC
BodneyC

Reputation: 110

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

Upvotes: 1

Views: 83

Answers (2)

abacles
abacles

Reputation: 859

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.

Upvotes: 8

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

you could do a ternary expression using the fact that printf( is equivalent to fprintf(stdout,:

fprintf(flag == 1 ? pt : stdout, "Random text...");

Upvotes: 2

Related Questions