Reputation: 1774
I'm using someones library that printf's out an error message when a connection to a device is unsuccessful. The library code prints out nothing when a connection is successful.
I periodically check (loop & sleep) to see if a device is connected but I only want to print out when it is connected.
At the moment I get something like:
Waiting for connection... (<-- My print)
Error
Error
Error
Error
Error
Connection successful (<-- My print)
What I want is:
Waiting for connection... (<-- My print)
Connection successful (<-- My print)
How can I programatically ignore a printf?
N.b. I found a similar question Programmatically Ignore Cout but that solution did not work for printf.
I am using Windows.
Can anyone help? (c/c++ novice)
Upvotes: 7
Views: 1120
Reputation: 1925
If you are using c++11 and above you can use a simple variadic template without much coding so this overloads printf
for all cases and the original one never gets called
template <typename ...Args>
void printf(Args... ...)
{
}
Upvotes: 0
Reputation: 18429
I don't know the absolute solution, but you'll need to use:
freopen("conout$", "w", stderr);
Or something similar, but with "conout$" pseudo-file, which I believe is same as /dev/stdout
on Linux.
You may have to use GetStdHandle
, AttachConsole
etc.
Upvotes: 0
Reputation: 9997
I was able to get this working under Linux the following way
#include <cstdio>
using namespace std;
int main() {
printf("Start\n");
freopen("/dev/null", "w", stdout);
printf("middle\n");
freopen("/dev/stdin", "w", stdout); // really stdin here!
printf("End\n");
return 0;
}
Under Windows I think there are other names for files (nul
and con
maybe).
However, this seems to be completely unportable, and, what's worse, this will prevent the users from redirecting your program output to a file, because I explicitly reopen /dev/stdin
. There are suggestions that you can use /dev/fd/1
instead of /dev/stdin
to mitigate the latter problem, but I have not tested it.
It seems that there is no reliable way, see, e.g. http://c-faq.com/stdio/undofreopen.html
Upvotes: 0
Reputation: 13988
Have you tried something like (before establishing connection):
FILE * myout = stdout;
stdout = fopen ("standard-output-file", "w");
To print something to output you could use then:
fprintf(myout, "format", ...);
Edit: Remember to close the file descriptor afterwards:
fclose(myout);
Upvotes: 2