我们如何在 C++ 中使用批处理文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1478171/
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
how can we use a batch file in c++?
提问by Todd
MY PURPOSE: I want to make a c++ program that could use DOS commands.
我的目的:我想制作一个可以使用 DOS 命令的 C++ 程序。
OPTION: I can make a batch file and put into it the DOS commands. But I don't know how to use this file from a c++ program?
选项:我可以制作一个批处理文件并将 DOS 命令放入其中。但我不知道如何从 C++ 程序中使用这个文件?
回答by Todd
There are two options available to run batch files on Windows from C/C++.
有两个选项可用于从 C/C++ 在 Windows 上运行批处理文件。
First, you can use system(or _wsystem for wide characters).
首先,您可以使用system(或 _wsystem 用于宽字符)。
"The system function passes command to the command interpreter, which executes the string as an operating-system command. system refers to the COMSPEC and PATH environment variables that locate the command-interpreter file (the file named CMD.EXE in Windows 2000 and later)."
“系统函数将命令传递给命令解释器,后者将字符串作为操作系统命令执行。系统指的是定位命令解释器文件(Windows 2000 及更高版本中名为 CMD.EXE 的文件)的 COMSPEC 和 PATH 环境变量)”
Or you can use CreateProcessdirectly.
或者您可以直接使用CreateProcess。
Note that for batch files:
请注意,对于批处理文件:
"To run a batch file, you must start the command interpreter; set lpApplicationName to cmd.exe and set lpCommandLine to the following arguments: /c plus the name of the batch file."
“要运行批处理文件,您必须启动命令解释器;将 lpApplicationName 设置为 cmd.exe,并将 lpCommandLine 设置为以下参数:/c 加上批处理文件的名称。”
回答by luke
回答by Phil Miller
You probably want to look at the system
, ShellExecute
, and CreateProcess
calls, to figure out which one is appropriate in this scenario.
你可能想看看system
,ShellExecute
和CreateProcess
电话,要弄清楚哪一个是在这种情况下适当的。
回答by GibbSticks
//example that makes and then calls a batch file
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[])
{
ofstream batch;
batch.open("mybatchfile.bat", ios::out);
batch <<"@echo OFF\n";
batch <<":START\n";
batch <<"dir C:\n";
batch <<"myc++file 2 >nul\n";
batch <<"goto :eof\n";
batch.close();
if (argc == 2)
{
system("mybatchfiles.bat");
cout <<"Starting Batch File...\n";
}
}
回答by SKrat
Putting dos commands inside batch script seems like a good idea. Then you can of course use system
command.
将 dos 命令放在批处理脚本中似乎是个好主意。然后你当然可以使用system
命令。
But if your C++ program also needs stdout of the batch script you were running, you should try: _popen
or _wpopen
.
但是,如果您的 C++ 程序还需要您正在运行的批处理脚本的标准输出,您应该尝试:_popen
或_wpopen
.
For more info and code sample visit MSDN.
有关更多信息和代码示例,请访问MSDN。
回答by VNarasimhaM
You can use system call in c++ program to execute all the commands that C++ program gets from the user.
您可以在 C++ 程序中使用系统调用来执行 C++ 程序从用户那里获得的所有命令。