如何在C ++ / Linux中执行外部命令? [英] How can I execute external commands in C++/Linux?

查看:515
本文介绍了如何在C ++ / Linux中执行外部命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道哪个是在C ++中执行外部命令的最佳方式,如果有任何命令,如何获取输出?



编辑:我想我不得不告诉我,在这个世界上,我是一个新手,所以我想我需要一个工作榜样。例如,我要执行一个命令:

  ls -la 

解决方案

使用 a href =http://opengroup.org/onlinepubs/007908775/xsh/popen.html =nofollow noreferrer> popen 功能。 / p>

示例(未完成,生产质量代码,无错误处理):

  FILE * file = popen(ls,r); 
//使用fscanf读取:
char buffer [100];
fscanf(file,%100s,buffer);
pclose(file);


I just want to know which is the best way to execute an external command in C++ and how can I grab the output if there is any?

Edit: I Guess I had to tell that I'm a newbie here in this world, so I think I'm gonna need a working example. For example I want to execute a command like:

ls -la

how do I do that?

解决方案

Use the popen function.

Example (not complete, production quality code, no error handling):

FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);

这篇关于如何在C ++ / Linux中执行外部命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆