Shutdown and Restart a Computer using C++

In general, we can shut down and restart a computer by clicking the start menu or using shortcuts. We can also shut down and restart the computer using a simple code in C++.

In this article, we are going to learn how to shut down and restart a computer using some simple C++ codes. We can perform restart and shutdown of the system in many ways.

  • Shut down the computer immediately.
  • Restart the computer immediately.
  • Shut down the computer at default time(i.e., 30 sec)
  • Restart the computer at the default time.
  • Shut the computer after a specified time.
  • Restart the computer after a specified time.

C++ program to shut down and restart a computer :

In order to shut down or restart a computer we will be using system() function which is present in stdlib.h header file.  We will pass corresponding commands to this system() function for restarting and shutting down the system. Then this function invokes the command prompt or terminal in windows and Linux systems respectively.

Below are the commands to shut down and restart a computer at default time :

Shut down :  "C:\\Windows\\System32\\shutdown /s"
Restart : "C:\\Windows\\System32\\shutdown /r"

In order to shut down and restart the system at a specified time we use the below commands by adding the specified time after “\t” :

Shut down : "C:\\Windows\\System32\\shutdown /s /t "

Restart : "C:\\Windows\\System32\\shutdown /s /t "

If we want to shut down immediately we can add “0” at the end of the shutdown command and pass it to the system() function. Similarly restart also.

command : "C:\\Windows\\System32\\shutdown /s /t 0"

We can also add any specific time like 40 sec at the end of the commands. So that the computer will shut down or restart after that specified time only. Or we can read the specified time from the user and convert it into a string and add it at the end of the command before passing to system() function.

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    int op;
    cout << "1. Shutdown Your Computer at default time\n";
    cout << "2. Restart Your Computer at default time\n";
    cout << "Enter your choice: ";
    cin >> op;

    switch (op)
    {
        case 1:
            cout << "1. Shutdown Your Computer at default time\n";
            system("C:\\Windows\\System32\\shutdown /s \n\n");
            break;
        case 2:
            cout << "2. Restart Your Computer at default time\n";
            system("C:\\Windows\\System32\\shutdown /r \n\n");
            break;
        default:
            cout << "Choose right one\n";
            break;
    }

    return 0;
}

Above is a simple code to shut down and restart the computer at the default time which is 30 seconds. We have used a switch case so the user can choose whether to restart or shut down the system.

Leave a Reply

Your email address will not be published. Required fields are marked *