I have come across many questions related to this but my requirement is quite different. I developed a C application(mib-test.c) earlier which uses fprintf at lot of places. fprintf logs the messages in a file.
But now I need to print these messages to console also. I am looking for a solution in which I do not need to change fprintf in all the places.
Is there a way to do it?
No, there is not, you will have to edit each instance. A better approach to begin with would have been to create your own logging function or macro. I would suggest you to do that now, and save yourself some time if you ever change mind again in the future.
Example using a function:
void log(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
va_start(args, fmt);
vfprintf(logfile, fmt, args);
va_end(args);
}
Example using a macro:
#define log(fmt, ...) do { \
fprintf(stderr, fmt, __VA_ARGS__); \
fprintf(logfile, fmt, __VA_ARGS__); \
} while (0)
See also: do { ... } while (0) — what is it good for?
Note that using a macro will evaluate expressions twice. For example log("%d\n", get_int()); using the macro form will call get_int() twice. You should only use the macro if you plan to pass simple values.
Both solutions assume that logfile is global and already opened for writing. You could actually define it static inside the function and handle the initial opening checking if (logfile == NULL) before doing anything.
@marcobonelli wrote a great answer. So for the replacing part, if you're not using an IDE that can do all the replacements for you, you could probably use this simple sed command to do all the replacement. Assume you have a log function like in this answer, then just do this:
sed 's/fprintf(logfile/log(/g' -i <file>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With