Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent function from printing?

Tags:

c

gcc

printf

Is it possible to silence a function? For example:

#include <stdio.h>
int function(){
  printf("BLAH!");
  return 10;

}
int main(){
  printf("%d", silence( function()) );
return 0;
}

And instead of:

BLAH!
10

I would get:

10

Is it possible? If positive how to do it?

like image 753
PovilasID Avatar asked May 11 '13 14:05

PovilasID


2 Answers

An awfully complicated way to do almost what you want is to use the dup2() system call. This requires executing fflush(stdout); dup2(silentfd, stdout); before function() is called, and copying back afterwards: fflush(stdout); dup2(savedstdoutfd, stdout);. So it is not possible to do as just silence(function()), since this construct only allows to execute code after function() has already been executed.

The file descriptors silentfd and savedstdoutfd have to be prepared in advance (untested code):

 int silentfd = open("/dev/null",O_WRONLY);
 int savedstdoutfd = dup(stdout);

This is almost certainly not what you really want, but inasmuch as your question is phrased as “is it possible?”, the answer is “almost”.

like image 71
Pascal Cuoq Avatar answered Oct 03 '22 12:10

Pascal Cuoq


use macro function and null device.

E.g. for windows

#include <stdio.h>

#define silence(x) (_stream = freopen("NUL:", "w", stdout), _ret_value = x,_stream = freopen("CON:", "w", stdout),_ret_value)
int _ret_value;
FILE *_stream;

int function(){
  printf("BLAH!");
  return 10;

}
int main(void){
    printf("%d", silence( function()) );
    return 0;
}
like image 20
BLUEPIXY Avatar answered Oct 03 '22 12:10

BLUEPIXY