使用 C++ 执行 CMD 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31201631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:53:35  来源:igfitidea点击:

Execute CMD commands using C++

c++windowscmdcommand

提问by John

In my project I want to execute some CMD commands. What is the syntax for doing that using C++.

在我的项目中,我想执行一些 CMD 命令。使用 C++ 执行此操作的语法是什么。

采纳答案by Ron

You can execute Windows Command prompt commands using a C++ function called system();. For safer standardsyou are recommended to use Windows specific API'S like ShellExecuteor ShellExecuteEx. Here is how to run CMD command using system()function.

您可以使用名为system();. 为了更安全的标准,建议您使用 Windows 特定的 API,如ShellExecuteShellExecuteEx。以下是如何使用system()函数运行 CMD 命令。

You should place the CMD command like shown below in the program source code:

您应该在程序源代码中放置如下所示的 CMD 命令:

system("CMD_COMMAND");

Here is a program which executes the DATE command in CMD to find the date:

这是一个在 CMD 中执行 DATE 命令来查找日期的程序:

#include <iostream>
using namespace std;

int main() {
    system("DATE");
    return 0;
}

回答by Ajay

Use Windows specific APIs:

使用 Windows 特定的 API:

See thisalso.

见这个

回答by user7233039

I suppose you could always do:

我想你总是可以这样做:

#include <iostream>
#include <windows.h>

using namespace

int main()
{
    WinExec("cmd", 1);
    return 0;
}

This however, automatically sets the path to the folder your file is in. Just type cd\ to return to base file.

但是,这会自动设置文件所在文件夹的路径。只需键入 cd\ 即可返回基本文件。