I have a program that i am including in another program . I want to redirect what it prints using printf statements to a file or a string. Can i change the standard out put of where printf prints ?
I have a program that i am including in another program . I want to redirect what it prints using printf statements to a file or a string. Can i change the standard out put of where printf prints ?
Do you mean your code is calling another executable, or you have code that you're compiling together with other code?
"I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008
"the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010
I have code that is compiling with another code.
Which operating system / compiler are you using for your code?
What do you want to do "with the file" when the other program has finished?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
If you have the code, why don't you change the printf's to fprintf or sprintf as appropriate?
I know how to redirect stdout to a file in C++ but I'm not sure it's C. I don't ever program in pure C.
I use freopen() which will redirect std::out to a file. Note that in Visual Studio to redirect back to the console you must pass in "CON" as the filename. This is a little caveat of freopen() that is not mentioned in the docs for MSVS. I found it on MSDN after searching forever.
I'm not sure if this affects printf() but if it is going to std::out internally then it will work for printf.
You can use an output redirection on file execution, like this..
Example..Code:./filename >> textfile.txt
Will output in textfile.txtCode:#include <stdio.h> int main () { printf("Hello World \n"); return 0; }
Or you can use fprintf..Code:Hello World
Code:fprintf( stderr, "My name is PC" ); //stderr is the console, you can change it to a file, cause it's a file descriptorOr you can also use freopen, as Bubba said..Code:int fprintf(FILE *file, const char *text, ...);
Example..Code:FILE *freopen(const char *path, const char *mode, FILE *stream);
Code:freopen( "result.txt","wb",stdout ); // closes stdout and redirects output to result.txt
Last edited by lautarox; 09-20-2008 at 08:53 AM.