0

I have a legacy program which outputs to either stdout or a file if given a -o option.

if (<-o option exists>) {
  fn = fopen(file_name, "w");
} else {
  fn = stdout;
}

I want to change this program to output to nowhere (minimal fileio overhead). At first, I'm considering:

if (<-o option exists>) {
  fn = fopen(file_name, "w");
} else {
  fn = fopen("/dev/null", "w");
}

I'm trying to simply measure the compute time of the program without any fileio. Since I don't want GCC to just blow away the compute parts (and also it's legacy code), I would like the code path to actually output the results to exist, but have the program have the option to fputc, putc, printf, etc. to nothing. The program seems to mix all 3 methods of printing unfortunately and I'd have to do a lot of surgery to remove it.

Is there a FILE* pointer I can give to those functions that would cause them not to do anything and not throw exceptions? And one that's preferably portable.

jkang
  • 483
  • 7
  • 19
  • 4
    You could pass in `/dev/null` as the output file and/or redirect the output to `/dev/null`. – dbush Apr 17 '23 at 18:51
  • 1
    On Windows you can use the name `NUL` instead of `/dev/null`. – Jabberwocky Apr 17 '23 at 18:52
  • [Related question](https://stackoverflow.com/questions/54196197/) – user3386109 Apr 17 '23 at 18:53
  • `file descriptor` Watch out - `fopen` returns a FILE* pointer, not a file descriptor. File descriptors are just `int`, returned by `open` (and many other interfaces) on Linux and are very different from FILE*. – KamilCuk Apr 17 '23 at 19:01
  • I guess I meant FILE* pointer. Not file descriptor. Changing the question. – jkang Apr 17 '23 at 19:03
  • 1
    Since this is for a one-off measurement, you can use macros for the functions that take a `FILE *`: `#undef fprintf` / `#define fprintf(file,...) ((file) ? fprintf((file), __VA_ARGS__) : 0)`. – Eric Postpischil Apr 17 '23 at 19:10
  • 1
    It is not clear whether what you want to do about `printf` and `putc`, since those output to `stdout` and you have not indicated any way to tell them whether you want output or not. If you want all of them to do nothing, that is easy. If you want to disable some of them selectively, you need to indicate how that will be distinguished. – Eric Postpischil Apr 17 '23 at 19:11
  • Thanks @EricPostpischil I didn't realize you could #undef fprintf. I'll give that a try! – jkang Apr 17 '23 at 19:21

1 Answers1

0

There is a file in the path /dev/null.

theprogram -o /dev/null

You can also just redirect stdout of the program to /dev/null using shell, typically:

theprogram >/dev/null
KamilCuk
  • 120,984
  • 8
  • 59
  • 111