using linux commands in C++ code

heidik's Avatar, Join Date: Oct 2010
Contributor
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

Code:
./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?
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
system() is your friend.
0
heidik's Avatar, Join Date: Oct 2010
Contributor
xpi0t0s could you please explain to me with an example code.
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
from the command line:

$ runApp

within a C program:

system("runApp");

I think redirection works too; not sure, you'd need to check. I think system spawns a shell so all shell features should work as expected - however you need to consider what the current directory is, so if the executable is running from a path location rather than the current directory then the redirect may need to specify a path rather than just a filename if the output file is to be located where you expect.
0
heidik's Avatar, Join Date: Oct 2010
Contributor
ok Thanks

someone suggested me this example "http://www.cplusplus.com/reference/iostream/ios/rdbuf/" which I found a bit easier and it worked as well but not when I tried to use it with the output of this command

Code:
system("diff /home/test1.txt /home/test2.txt");
Do you have any idea why? it still prints the output on to the screen and not to a file.
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Where would be the bit that tells it to write the output to a file?