Arbok
Arbok

Reputation: 63

Is it possible to print on a file the output of a function?

I'm writing a tool which uses various void functions to analyze some elements that the program receive in input, and print in the stdout (using printf()) the results of the analysis. Obviously that means that i use printf() very much, because there are lots of things that need being printed. I would like that everything is printed on the stdout, is printed also on a log file. But the use of fprintf() for each printf() function makes the program really longer, confused and not well-ordered. Is there a way to save directly the output of a function on a file? So if i have a void function for example analyze() wich contains lots of printf() functions, the output of analyze() will be printed in the stdout (to the shell) and also on a file. I tried to look for it but withouth any results. Thanks for help guys!

Upvotes: 0

Views: 73

Answers (2)

RonaldBarzell
RonaldBarzell

Reputation: 3830

You could write a function that will issue a printf and fprintf and call that function instead.

For instance, here's a skeleton, obviously you'll have to fill in the ...:

void myPrintf(...) 
{
     printf(...);
     fprintf(...);
}

Then in your code, instead of printf, you could call:

myPrintf(...);

You could also do this with a macro.

If you need to turn off logging, you could do so by simply pulling out the fprintf in that function and leave the rest of your code unchanged.

Upvotes: 1

JasonD
JasonD

Reputation: 16612

It's generally better to have a specialised logging function, rather than peppering your code with direct printf/fprintf calls. That logging function can write to stdout, a log-file, whatever you want, and can be different in debug/release, etc.

Upvotes: 1

Related Questions