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?
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 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.
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."