In Linux programming, you often need to call some system commands or shell scripts to help us complete some operations. In most cases, the system function is competent, but sometimes after the operation is completed, we need to get its output, and the system function is powerless. For this reason, I have compiled a function that allows the system to execute a command first and then use the pipeline technology to obtain its output. Code:
# Include <sys/types. h> # include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <string. h> # define maxline 1024 // call the system command and obtain the output (equivalent to using system) // input: The system command to be called // output: system output after the command is called // maxlen: Maximum length of the output string int mysystem (char * input, char * output, int maxlen) {If (null = input | null = output) Return-1; int reslen; file * stream; memset (output, 0, maxlen); // create a pipeline, and write the content in the input to the pipeline stream = popen ( Input, "R"); // read data from the management and write the output array reslen = fread (output, sizeof (char), maxlen, stream); pclose (Stream ); return reslen;} int main (INT argc, char ** argv) {If (argc! = 2) {fprintf (stderr, "using :. /mysystem <cmd> \ n "); exit (1);} Char output [maxline]; mysystem (argv [1], output, maxline ); printf ("the result of '% s' is: \ n % s", argv [1], output); Return 0 ;}
Running example: qch @ Ubuntu :~ /Code $ GCC temp. C-o temp
Qch @ Ubuntu :~ /Code $./temp pwd
The result of 'pwd' is:
/Home/qch/code