我们如何在c ++中使用批处理文件?

11 c++ batch-file

我的目的:我想制作一个可以使用DOS命令的c ++程序.

选项:我可以创建一个批处理文件并将其放入DOS命令中.但我不知道如何使用c ++程序中的这个文件?

小智 14

有两个选项可用于在Windows上从C/C++运行批处理文件.

首先,您可以使用system(或_wsystem用于宽字符).

"系统函数将命令传递给命令解释器,命令解释器将字符串作为操作系统命令执行.系统是指定位命令解释器文件的COMSPEC和PATH环境变量(Windows 2000及更高版本中名为CMD.EXE的文件) )".

或者您可以直接使用CreateProcess.

请注意,对于批处理文件:

"要运行批处理文件,必须启动命令解释程序;将lpApplicationName设置为cmd.exe并将lpCommandLine设置为以下参数:/ c加上批处理文件的名称."


Phi*_*ler 6

你可能想看看system,ShellExecuteCreateProcess电话,要弄清楚哪一个是在这种情况下适当的.


小智 6

//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";
    }
}
Run Code Online (Sandbox Code Playgroud)