Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Redirection of output 2

Status
Not open for further replies.

IcedBear

Technical User
Jul 29, 2005
3
DE
Hello!

As far as I know, in C++ it is possible to redirect output into streams. I now got the problem that I have to work with some data I get back from a system-command. I call that command with system("foo"); , but unfortunately it writes the command output to stdout. I tried "ostringstream reply; reply << system("foo")" but I only got the (int) return value of system, but not the result from the command called. Anyone got an idea?
BR, Björn
 
Assuming you cannot modify the foo program, if you want to read the output of a process run through a system call, you should redirect the output of that call to a file, then open the file in your program. For example:
Code:
system("foo > out.txt");
std::ifstream fooOutput("out.txt");

// ... use fooOutput
 
popen can do input and output to any program "foo"

C example of catching output (from C forum):
Code:
#include <stdio.h>

main()
{
  FILE *fp;
  char line[130];/* line of data from unix command*/
   
  fp = popen("foo", "r");/* Issue the command.*/

/* Read a line*/
  while ( fgets( line, sizeof line, fp))
  {
    printf("%s", line);
  }
  pclose(fp);
}

[plug=shameless]
[/plug]
 
It is much wiser to use popen as suggested by myself and subsequesntly jstreich since the file solution causes unneccessary overhead and worse, the risk of failure due to permissions, and the risk of treading on someone else's file unless you are really careful with filenames and space.

Trojan.
 
Even worse than that, if the file is writen, and the contents are sensitive, (depending on user's umask) others may be able to read the information. i.e. the program generates a secure hash like SHA key.

[plug=shameless]
[/plug]
 
Thank you all, the popen was exactly what I needed :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top