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

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

问题描述

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

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

我该怎么做?

推荐答案

使用popen 函数.

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

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天全站免登陆