C++ calls batch commands or .bat (.cmd) files or .exe files

Overview

The system() function in the header file stdlib.h (cstdlib) can be used to call batch commands, execute batch files, and run executable programs . Its function prototype is int system(char *command):;

Program demonstration

File Test.cpp

#include <iostream>
#include <cstdlib>

int main()
{
    
    
	system("ECHO HELLO WORLD WITH COMMAND"); // line 1
	system("HelloWorld.cmd"); // line 2
	system("HelloWorld.exe"); // line 3

	return 0;
}

The results of the operation are:

HELLO WORLD WITH COMMAND
HELLO WORLD IN CMD
HELLO WORLD IN EXE

description

Line1 executes the batch command;
line2 executes the batch file.
Line3 executes the exe file.

注意:此时HelloWorld.exe与HelloWorld.exe必须位于Test.cpp同目录下。

Batch processing commands

When using the system()call batch command, just use the command + parameter directly .

Two .bat (.cmd) files

When using system()a batch file, you should also pay attention to the path of the batch file. If you don't want to add the path of the file, be sure to put it in system()the directory where the function call is located . Otherwise, the path of the file must be added, which can only be an absolute path, not a relative path .

In addition, the file path must pay attention to the format; for example, for a file with a path
C:\Users\Administrator\Desktop\HelloWorld.exe,
the calling method must be:
system("C:\\Users\\Administrator\\Desktop\\HelloWorld.exe");the symbol "\" needs to be escaped, the difference between forward slash / and backslash \
If written as
system("C:\Users\Administrator\Desktop\HelloWorld.exe");

When editing, there will be a prompt as follows: a warning will be given
Insert picture description here
when compiling :

1>C:\Users\Administrator\Desktop\Project1\Project1\main.cpp(10,9): warning C4129: “A”: 不可识别的字符转义序列
1>C:\Users\Administrator\Desktop\Project1\Project1\main.cpp(10,9): warning C4129: “D”: 不可识别的字符转义序列
1>C:\Users\Administrator\Desktop\Project1\Project1\main.cpp(10,9): warning C4129: “H”: 不可识别的字符转义序列

The following prompt will be displayed during execution :

'C:UsersAdministratorDesktopHelloWorld.exe' 不是内部或外部命令,也不是可运行的程序或批处理文件。

Another possible calling method is as follows ( "/" does not need to be escaped ):
system("C:/Users/Administrator/Desktop/HelloWorld.exe");

Three.exe file

The precautions are the same as the .bat (.cmd) file.

Guess you like

Origin blog.csdn.net/xp178171640/article/details/113701042