C++ Popen
From wikinotes
Basic Example
#include <iostream> #include <stdio.h> #define DATA_SIZE 512 using namespace std; int main() { FILE *cmdprompt; char data[DATA_SIZE]; cmdprompt = popen("hostname", "r"); // Creates Pipe to cmd called cmdprompt - executes hostname fgets(data, DATA_SIZE , cmdprompt); // Grab data from process execution cout << data; // Print grabbed data to the screen. pclose(cmdprompt); cout << "Press Enter to Continue:"; std::cin.get(); }
Using a String Variable in popen
popen will only use a specially formatted const char Variable - not a string Variable.
//VARIABLES const char *tempChar; string myString = "Hello World"; tempChar = myString.c_str(); sprintf(command, tempChar); //formats the char to the format for a stream cmdprompt = popen(command, "r"); //commands while cmdprompt pipe is open pclose(cmdprompt);