13

MY PURPOSE: I want to make a c++ program that could use DOS commands.

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?

BUY
  • 705
  • 1
  • 11
  • 30

6 Answers6

15

There are two options available to run batch files on Windows from C/C++.

First, you can use system (or _wsystem for wide characters).

"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)."

Or you can use CreateProcess directly.

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."

Joey
  • 344,408
  • 85
  • 689
  • 683
Todd
  • 2,321
  • 14
  • 11
  • Is `::CreateProcess(L"cmd.exe"` really works ? I got error 2, ERROR_FILE_NOT_FOUND. BUT, In the same call, if I replace with `L"c:\\Windows\\System32\\cmd.exe"`, then it miraculously works ... – Liviu Jan 16 '18 at 12:31
13
system("mybatchfile.bat");

system() reference

luke
  • 36,103
  • 8
  • 58
  • 81
8
//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";
    }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
GibbSticks
  • 81
  • 1
  • 1
6

You probably want to look at the system, ShellExecute, and CreateProcess calls, to figure out which one is appropriate in this scenario.

Phil Miller
  • 36,389
  • 13
  • 67
  • 90
1

Putting dos commands inside batch script seems like a good idea. Then you can of course use system command.

But if your C++ program also needs stdout of the batch script you were running, you should try: _popen or _wpopen.

For more info and code sample visit MSDN.

SKrat
  • 11
  • 1
0

You can use system call in c++ program to execute all the commands that C++ program gets from the user.

VNarasimhaM
  • 1,460
  • 3
  • 22
  • 36