using linux commands in C++

Hello Everyone.

I wanted to know if there is any way I can use linux commands in C++. I want to store the output of a program in a file which is otherwise displayed on the screen using cout. I want that output to be stored in a file instead of displaying it on the screen. For example I write

./runApp > abc.log

on the command line and it writes the output in a file called abc.log. So is there any way I can use this command inside C++ code?
To run a shell command use system("your shell command");
To redirect the output of your own program use rdbuf http://www.cplusplus.com/reference/iostream/ios/rdbuf/
To run other programs use system specific library functions like fork, pipe and alike. see http://linux.die.net/man/2/pipe for an example
Use fork() to create a child process.

In the child process:
open the file 'abc.log' for writing using the open() system call.
use the close system call to close stdout and stderr (file descriptors 1 and 2 respectively)
then use the dup2 function to duplicate the file descriptor you got from step #1 to file descriptors 1 and 2
lastly, use one of the exec*() family of functions to execute the linux command you want to run.

In the parent:
Use waitpid() on the pid of the child process (return value from fork()) to wait for the child to exit
Read the contents of 'abc.log'.
Thanks Bazzy :)
Thanks JSmith :). I am new to linux so dont know much about it. I just want to compare the out of one file to another and instead of writing the file name each time I run the program, I wanted to use the same linux command inside the code.

Thanks anyway
Bazzy! The cout command is written in many different functions and not just one function. How can I use your example in this case?

your example: http://www.cplusplus.com/reference/iostream/ios/rdbuf/
Put lines 7-14 at the beginning of your program and it should work. When you want to restore the original destination of cout call cout.rdbuf(backup); ( you may need to pass backup if you want to do so in one of your functions )
Bazzy could you please tell me what do u mean by the beginning of program? r u talking about the main method? Main() is written in another cpp file where as all the cout statements are written in a separate class? Where do I have to write these lines of code in that case?
Anywhere that allows you to keep the file stream on scope and that is executed before any call of output operations on cout.
The beginning of main is a good place
Bazzy! I did not understand "Anywhere that allows you to keep the file stream on scope and that is executed before any call of output operations on cout."
Topic archived. No new replies allowed.