I have a program which prints (by printf) to the stdout some data and also calls to function *foo* which also prints to the stdout some data [the way (implementation) of how printing is done from foo is unknown and I can`t see the code of foo].

I have to redirect everything from stdout to buffer or file. I tried to do it in several ways

  1. freopen(file.txt, stdout) - only my code prints are written to the file.txt. What was printed from foo is lost.
  2. setbuf(buffer, stdout) - only my code prints are written to the buffer. What was printed from foo is appears in the stdout.(It appears on the screen)

What can explain this behavior? How can the problem be solved?

Note:This code has to work in cross-OS( lunux/wind && mac OS).I use gcc in order compile the code and I have cygwin

You're trying to print to the file or buffer, from within the IDE, aren't you?

That's not what you want. Run it from the command line.

Open a terminal (aka text window, command line interface, etc.) window. If you are not in the same directory as the exe of your program, change over to that directory. Now enter the name of your compiled file (your program), and add the redirect symbol:

myProgramsName > fileName

Your programs output to standard output, will be redirected to fileName file.

Redirection works for every operating system I am familiar with - Unix, Linux, DOS, Windows (all versions), BSD, etc.

If the program explicitly sends output someplace else, then this won't work.

Give that a try. ;)

Edited 5 Years Ago by Adak: n/a

I want to redirect it to buffer.Its a really test code for some function.I don't want to do it from command line

Of course you do! ;)

That's a new one to me. I don't know how to do what you want. Any Google hits for "redirect stdout to a buffer, in C"?

Edited 5 Years Ago by Adak: n/a

It does redirect but only from my main function.I used setbuf as I wrote in my first post.

Naturally, you can write data to a buffer you control - thought you understood that was no problem. It's getting the foo function to do it, that's the part I don't know.

I have always had full access and control of the functions, for the programs I wrote.

It does redirect but only from my main function.

Is this other function coming from a DLL or something? Your described behavior suggests that the two functions are using different instances of stdout, or foo() is using some other method to write to standard output. You haven't provided enough information about this program.

I used setbuf as I wrote in my first post.

setbuf() is strictly for optimization, it doesn't redirect anything.

This article has been dead for over six months. Start a new discussion instead.