38

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

1
  • 2
    Lookup for the system() function. Commented Jul 3, 2015 at 8:02

3 Answers 3

42

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

system is evil, unsecure, from C - use newer approaches. [1] stackoverflow.com/questions/1107705/systempause-why-is-it-wrong [2] cplusplus.com/forum/articles/11153
7

Use Windows specific APIs:

See this also.

Comments

3

I suppose you could always do:

#include <iostream>
#include <windows.h>

using namespace

int main()
{
    WinExec("cmd", 1);
    return 0;
}

This however, automatically sets the path to the folder your file is in. Just type cd\ to return to base file.

1 Comment

Isn't WinExec deprecated and therefor not wise to use?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.