5

This seems like a bit of a computing systems 101 question, but I'm stumped.

I am integrating existing code from C/C++ project A into my own project B. Both A and B will be linked into a single executable, threaded process. Project A's code makes extensive use of printf for output. This is fine, but I want also to capture that output into my own buffers. Is there a way I can read from stdout once the printf calls have written to it? I cannot fork the process or pipe. And my efforts to poll() stdout, or to dup() it, have not succeeded (I may be doing something wrong here).

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
MapMaker
  • 53
  • 1
  • 3

4 Answers4

4

You can use freopen to change the descriptor.

#include<stdio.h>

main(int argc, char** argv) {
    FILE *fp = freopen("output.txt", "w", stdout);
    printf("Hello\n");
    fclose(fp);
}

If you run that you'll see the printf output in output.txt and nothing will go to your screen.

You can now open the file to read the data or you could even mmap it into your memory space and process it that way.

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
3

Before you printf(), you could close fd 1, and dup2() a pipe that you've created into fd 1.

chmeee
  • 3,608
  • 1
  • 21
  • 28
1

Not to mention: there is now a handy U-Streams C source code library that makes redirecting stdout and stderr quite trivial. And you can even redirect them very easily to multiple destinations. And, you can create your own streams besides that can be used in exactly the same way stdout and stderr behave.

Look for the U-Streams C Library... handy indeed.

john
  • 11
  • 1
0

Once it's gone out, it's gone. If you want to compile it all into a single executable, you'll have to go through the code for A with a search and replace and change all those printf calls into ones to your own stream, where you can copy them and then pass them on to stdout.

Nicholas Wilson
  • 9,435
  • 1
  • 41
  • 80
  • Nick, this indeed was the work-around I implemented, but was hoping that I was simply doing something wrong with poll() and dup(). Ah well, time to move forward! Thanks for the answer. btw I like your icon :) – MapMaker Sep 02 '11 at 17:23
  • It's flushed and goes off to do its thing. The whole idea of pipes and stdout is that applications don't keep these things around; they buffer just as much as they need, then get rid of it immediately. That way piping applications together doesn't take much memory. There's no way to get that if you design things so that all the previous output sticks around for use later. – Nicholas Wilson Sep 02 '11 at 17:26
  • You could always do `#define printf(...) fprintf(myfile, __VA_ARGS__)` – Chris Lutz Sep 02 '11 at 20:01