简体   繁体   English

如何使用C ++与命令提示符(CMD)进行通信?

[英]How can I communicate with Command Prompt (CMD) using C++?

I have an application that need to send command to cmd and then get the ouput back (capturing the output). 我有一个应用程序,需要向cmd发送命令,然后返回ouput(捕获输出)。 How can this be accomplished using C++ without using any MS Windows specific API? 如何在不使用任何MS Windows特定API的情况下使用C ++实现这一目标? Is there a way that this may be done to be cross platform (for linux terminals for example)?. 有没有办法可以做到跨平台(例如对于linux终端)? By the way i'm on win XP SP3. 顺便说一句,我在赢得XP SP3。

I actually mean redirecting the input/output. 我的意思是重定向输入/输出。 For example, run the command "make" on cmd and then in case of error capturing the error message (redirecting to my application). 例如,在cmd上运行命令“make”,然后在错误捕获错误消息的情况下(重定向到我的应用程序)。

As mentioned: if you can avoid launching child processes in your program and instead fit into the broader "toolbox metaphor," that can often be better... 如上所述:如果您可以避免在程序中启动子进程,而是适应更广泛的“工具箱隐喻”,那通常会更好......

http://en.wikipedia.org/wiki/Unix_philosophy http://en.wikipedia.org/wiki/Unix_philosophy

But if that's not a fit for your project, check out Boost.Process . 但如果这不适合您的项目,请查看Boost.Process

Also: if you're using Qt (which is good to look at in any case) there is also QProcess . 另外:如果您正在使用Qt(在任何情况下都很好看),还有QProcess

Can't you just use the regular cin and cout that C++ provides? 难道你不能只使用C ++提供的常规cin和cout吗? (of course if your program is a GUI program, cin and cout won't be connected to anything useful unless you call the Windows AllocConsole() command... but that's just the way Windows works. If you want code that also compiles under Linux, etc, you can put #ifdef WIN32 around that call) (当然,如果你的程序是一个GUI程序,除非你调用Windows AllocConsole()命令,否则cin和cout将不会连接到任何有用的东西......但这只是Windows的工作方式。如果你想要编译的代码也是如此Linux等,你可以把#ifdef WIN32放在那个调用上)

系统()函数是C89和C99标准的一部分,可在Linux和Windows上使用,并允许在C / C ++中执行命令。

By default, most systems get their standard input from the keyboard, therefore cin is generally expected to get information from the user, although there are many cases where this can be redirected to some other source. 默认情况下,大多数系统从键盘获取标准输入,因此通常期望cin从用户获取信息,尽管在许多情况下可以将其重定向到其他来源。

You can do something like: 你可以这样做:

cout << "How old are you?" << endl;
int age;
cin >> age;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM