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
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.
You can use system call in c++ program to execute all the commands that C++ program gets from the user.
You probably want to look at the system
, ShellExecute
, and CreateProcess
calls, to figure out which one is appropriate in this scenario.
//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";
}
}
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."
system("mybatchfile.bat");
system() reference