Execute shell commands using popen in c++

别来无恙 提交于 2019-12-23 05:14:22

问题


I need to be able to execute some shell commands such as moving to the right directory where I have some files I need to decode and then decoding them using another command. I read some stuff about using popen but I didnt really understand how to use it for executing multiple commands.

Any pointers will be greatly appreciated :)

Thanks

FILE *pf;
char command[150];
char data[512];

// Execute a process listing
sprintf(command, "cd");
pf = _popen(command,"r"); 

sprintf(command, "cd Test_copy");
pf = _popen(command,"r");   */

sprintf(command, "java -jar Tool.jar -b x.fit x.csv"); 
pf = _popen(command,"r"); 

if(!pf){
  fprintf(stderr, "Could not open pipe for output.\n");
  return;
}

// Grab data from process execution
fgets(data, 512 , pf);

// Print grabbed data to the screen.
fprintf(stdout, "-%s-\n",data); 

if (_pclose(pf) != 0)
    fprintf(stderr," Error: Failed to close command stream \n");

回答1:


Use ShellExecute to play with files (open with default application etc.). Use system to run shell commands.




回答2:


No, don't. That would be like using a sledgehammer to knock on a door. Furthermore, it is "evil": http://www.cplusplus.com/forum/articles/11153/



来源:https://stackoverflow.com/questions/7207916/execute-shell-commands-using-popen-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!