Get Commad Line Output
Sometimes we need get the output from a cmd tool. Generally , the cmd output infomation into stdout or stderr.
We use two method to get the output from the cmd line then used in our application.
First, assume we have a cmd tool called cmdtool, the following command we can run on the termianl:
./cmdtool -i input_file -o output_file -a 1
1, popen
FILE *f_p = popen(cmd_str.toStdString().c_str(), "r"); QString p_output = ""; char buf[1024]; if (f_p != NULL) { while (fgets(buf, 1024, f_p) != NULL) { // DO SOMETHING } }
2, system
int PIPEDES[2]; /* Create a one-way communication channel (pipe). If successful, two file descriptors are stored in PIPEDES; bytes written on PIPEDES[1] can be read from PIPEDES[0]. Returns 0 if successful, -1 if not. */ if(pipe(PIPEDES)) // PIPEDES[0] read pipe, PIPEDES[1], write pipe { printf("pipe error, exit!"); return -1; } /* Duplicate FD, returning a new file descriptor on the same file. */ int bak_fd = dup(STDOUT_FILENO); /* Duplicate FD to FD2, closing FD2 and making it open on the same file. */ int new_fd = dup2(PIPEDES[1], STDOUT_FILENO); // output is write into fd[1] system(pComd); //write(PIPEDES[1], c, sizeof(c) / sizeof(c[0]) - 1); read(PIPEDES[0], result, size); dup2(bak_fd, new_fd); close(PIPEDES[0]); close(PIPEDES[1]); return 0;

浙公网安备 33010602011771号