C++ || Snippet – How To Use Popen & Save Results Into A Character Array
The following is sample code which demonstrates the use of the “popen” function call on Unix based systems.
The “popen” function call opens a process by creating a pipe, forking, and invoking the shell. It does this by executing the command specified by the incoming string function parameter. It creates a pipe between the calling program and the executed command, and returns a pointer to a stream that can be used to either read from or write to the pipe.
The following example demonstrates how to save the results of the popen command into a char array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
// ============================================================================ // Author: Kenneth Perkins // Date: Aug 20, 2013 // Taken From: http://programmingnotes.org/ // File: PopenExample.cpp // Description: Demonstrate the use of the popen() command and demonstrate // how to save the results into a char array. // ============================================================================ #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> using namespace std; // the maximum output size const int MAX_OUTPUT_SIZE = 1000; int main(int argc, char* argv[]) { // declare variables char buffer[MAX_OUTPUT_SIZE]; // a char array to display the popen output FILE* progOutput; // a file pointer representing the popen output // launch the "md5sum" program to compute the MD5 hash of // the file "/bin/ls" and save it into the file pointer progOutput = popen("md5sum /bin/ls", "r"); // make sure that popen succeeded if (!progOutput) { perror("popen"); exit(1); } // reset buffer to all NULLS memset(buffer, (char)NULL, sizeof(buffer)); // read the popen output into the char array buffer if (fread(buffer, sizeof(char), sizeof(char) * sizeof(buffer), progOutput) < 0) { perror("fread"); exit(1); } // close the file pointer representing the popen output if (pclose(progOutput) < 0) { perror("pclose"); exit(1); } cout << "Program output: " << buffer << endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
Program output: fa97c59cc414e42d4e0e853ddf5b4745 /bin/ls
Leave a Reply