Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 706
  • Last Modified:

Need Linux system call from C++ to send cout to a string

Youi've got some information here, but I can't get it to work. I need to call the system command on a Linux machine, and capture the output that would normally go to the terminal (cout) in a string (or stringstream).
For ex.:
prep string to receive what would normally go to cout
call system("ls -al" );
return cout to normal operation (sent to terminal)
1 Solution
     popen, pclose -- process I/O

     Standard C Library (libc, -lc)

     #include <stdio.h>

     FILE *
     popen(const char *command, const char *type);

     pclose(FILE *stream);

     The popen() function ``opens'' a process by creating a bidirectional pipe
     forking, and invoking the shell.  Any streams opened by previous popen()
     calls in the parent process are closed in the new child process.  Histor-
     ically, popen() was implemented with a unidirectional pipe; hence many
     implementations of popen() only allow the type argument to specify read-
     ing or writing, not both.  Since popen() is now implemented using a bidi-
     rectional pipe, the type argument may request a bidirectional data flow.
     The type argument is a pointer to a null-terminated string which must be
     `r' for reading, `w' for writing, or `r+' for reading and writing.

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now