Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute CMD commands using C++

In my project I want to execute some CMD commands. What is the syntax for doing that using C++.

like image 879
John Avatar asked Jul 03 '15 08:07

John


People also ask

Can C run CMD?

How to Compile C Program in Command Prompt? We usually use a compiler with a graphical user interface, to compile our C program. This can also be done by using cmd. The command prompt has a set of steps we need to perform in order to execute our program without using a GUI compiler.

How do I change to C in CMD?

Change Directory in CMD to C Drive This is how it's done: Run Command Prompt. You can find it by typing “CMD” in your search bar. Enter “ cd ” or “ chdir .”


2 Answers

You can execute Windows Command prompt commands using a C++ function called system();. For safer standards you are recommended to use Windows specific API'S like ShellExecute or ShellExecuteEx. Here is how to run CMD command using system() function.

You should place the CMD command like shown below in the program source code:

system("CMD_COMMAND"); 

Here is a program which executes the DATE command in CMD to find the date:

#include <iostream> using namespace std;  int main() {     system("DATE");     return 0; } 
like image 63
Ronald P Mathews Avatar answered Oct 02 '22 19:10

Ronald P Mathews


Use Windows specific APIs:

  • ShellExecute or ShellExecuteEx
  • CreateProcess

See this also.

like image 31
Ajay Avatar answered Oct 02 '22 19:10

Ajay