How to delete an empty directory in C

How to delete an empty directory in C

In this post, we will learn how to delete an empty directory using a C program. We will take the directory name as input from the user. The program will delete the directory if it exists.

With this post, you will learn how to take user inputs and how to use system() function to run a system command.

system function in C:

system() is a function available in C and C++, which can be used to run commands those can be executed from the command line. It is defined in stdlib.h and we need to use #include<stdlib.h> to use this function.

This function is defined as like below:

int system(const char* cmd)

It takes one parameter, cmd, which is the command we want to execute.

Its return value is an integer. For success, it returns 0, else it returns any other integer value.

How to use system function to delete an empty directory:

The command used to delete a directory is rmdir directory_path, where directory_path is the path of the directory. We will take the directory path as input from the user and by using this system function, we will delete that directory.

Below is the complete program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char dir[40];
    char cmd[40];

    int result = 0;

    printf("Enter the directory name you want to delete: ");
    scanf("%s", dir);

    sprintf(cmd, "rmdir %s", dir);

    printf("This is the command we are using: %s\n", cmd);
    result = system(cmd);

    if (result == 0)
        printf("It is deleted\n");
    else
        printf("Delete failed for the directory: %s\n", dir);

    return 0;
}

Here,

  • dir is a character array to keep the user given directory name, i.e. the directory name to delete.
  • cmd is another character array to keep the final system command we are passing to the system command. i.e. it is equal to rmdir dir_name.
  • We are using scanf to read the user input directory name. We are then using sprintf to create the final command and this is stored in cmd.
  • cmd is passed to system and its return value is stored in the variable result.
  • The last if-else block is checking the value of result. If it is equal to 0, it means that the folder is deleted. So, it prints a message that the folder is deleted. Else, it prints another message that the delete operation is failed.

Sample output:

It will give output as like below:

Enter the directory name you want to delete: tempfolder
This is the command we are using: rmdir tempfolder
It is deleted

Enter the directory name you want to delete: newfolder
This is the command we are using: rmdir newfolder
rmdir: newfolder: No such file or directory
Delete failed for the directory: newfolder

There was a folder tempfolder so the first one deleted the folder. There is not folder newfolder, so the second one throws one error that delete is failed.

You might also like: