views:

223

answers:

4

Hello, I'm writing program in C++ (for XAMPP communication) and I want to execute command which I have in strings (I know that this is simply system("command")) but I want to get the output from bash to C++ to string. I've founded several threads about this, but no which solved Bash -> C++.

+2  A: 

You need to call the popen function, and read the output from the FILE it returns.

Martin v. Löwis
+1  A: 

You can try Standard Output Redirection to redirect the standard output to a file stream and then use it to read to a string.

Dup()

Baget
Indeed, if the C++ program reads stdin then you can issue a cammand like: bash_command | cppProgram | string
Deverill
+3  A: 

You can call the FILE *popen(const char *command, const char *mode) function. Then, you can read the file it returns to get the output of your call.

It's like using a pipe to redirect the output of the command you used to a file in the hard drive and then read the file, but you don't get to create a file in the hard drive.

The documentation of the popen() is here.

jpmelos
A: 

Ok, any more ideas? Any popen looks good, but any way to do this without files? I must read manpage for dup.

Garret Raziel
The FILE* popen returns is not (necessarily) a real file and usually does not end up written to disk ever. (With large output this is not necessarily true.) FILE* is just an interface into a file-like device. When FILE* is created with fopen, it points to a real file on disk. When created with popen, there usually isn't a real file on disk.
jmucchiello