1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

using linux commands in C++ code

Discussion in 'C++' started by heidik, Nov 4, 2010.

  1. heidik

    heidik New Member

    Joined:
    Oct 23, 2010
    Messages:
    69
    Likes Received:
    0
    Trophy Points:
    0
    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?
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    system() is your friend.
     
  3. heidik

    heidik New Member

    Joined:
    Oct 23, 2010
    Messages:
    69
    Likes Received:
    0
    Trophy Points:
    0
    xpi0t0s could you please explain to me with an example code.
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     
  5. heidik

    heidik New Member

    Joined:
    Oct 23, 2010
    Messages:
    69
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  6. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Where would be the bit that tells it to write the output to a file?
     

Share This Page