Reputation: 1330
How can I overload/override printf in C++ in such a way that the following are true:
Every line printed to STDOUT is either prepended with or appended by the characters of my choosing.
The call to printf is not obscured - ie, I need to be able to call printf and have every line modified. I DO NOT want to call "myPrintf" or something like that.
Background
I am trying desperately to be able to build and view the standard text output of a program that uses the DXGI API from a *nix system. I have it working through a combination of an SSH server on my Windows system, Jenkins, and the Jenkins CLI.
The problem is that Jenkins, when it gives me the output from my build, does not flag the output of my program in a scriptable way - ie, it is garbled up with the output of my other build steps, as well as the general Jenkins output.
I would like to be able to somehow flag every line of my program's output with some known set of characters - that would allow me to pipe the output of my command through grep and get the actual log of my program. By keeping the printf calls un-molested, I would also be able to toggle this debug output with a macro definition.
EDIT
I am open to alternative suggestions - flagging the output of my executable somehow is definitely also an option, but it needs to work using functionality that works on the Windows server.
Basically, I have it to the point where I can type "make test" on my *nix machine and it will build and give me my (currently obscured) test output as if it was local, but the compilation and execution is actually happening remotely. This is pretty awesome - the last step for me is to de-obscure the test output.
Upvotes: 2
Views: 1379
Reputation: 899
Most convenient way:
#include <stdio.h>
#include <stdarg.h>
using namespace std;
int taggedPrintf(const char * format, ...){
printf("[PRE]");
va_list args;
va_start (args, format);
vprintf (format, args);
va_end (args);
printf("[POST]\n");
}
#define printf taggedPrintf
int main()
{
printf("your usual message");
printf("Testing numbers %d %f", 1,0.2);
return 0;
}
Another way: (Quick one) You can try defining abbreviations:
#define PRE printf("[PREFIX]");
#define POST printf("[SUFFIX]\n");
int main()
{
PRE
printf("your usual message");
POST
return 0;
}
Another approach: redirect the stdout to null device to block screen output
freopen("/dev/null", "a", stdout);
define a large string buffer
char largeBuffer[LARGE_ENOUGH];
Using setbuf send everything to this buffer
setbuf(stdout, largeBuffer);
.....
(Use printf as usual.)
.....
At the end you need to append and prepend your tags to each line or whole output and cancel redirection and finally print the tagged stream.
Upvotes: 1