Welcome 微信登录

首页 / 操作系统 / Linux / Linux C执行命令并保存到string中

  1. #include <stdio.h>   
  2. #include <string.h>   
  3.   
  4. #include "cmd_exec.h"   
  5.   
  6. #include "comm.h"   
  7.   
  8. string ExecCmd(const string & cmd)   
  9. {   
  10.     char store[kPipeMax], command[kCmdMax];   
  11.     string result;   
  12.     StrToCharStar(cmd, command);   
  13.     FILE *pfp = popen(command, "r");   
  14.     if (NULL == pfp)   
  15.         return result;   
  16.     memset(store, 0, kPipeMax);   
  17.     while (kPipeMax-1 == fread(store, sizeofchar), kPipeMax-1, pfp)   
  18.         && !feof(pfp)) {   
  19.             result += store;   
  20.             memset(store, 0, kPipeMax);   
  21.     }   
  22.     result += store;   
  23.   
  24.     return result;   
  25. }