C program to remove a non-empty directory using the system() function

Here, we are going to learn how to remove a non-empty directory using the system() function in C programming language?
By Nidhi Last updated : March 10, 2024

Problem statement

In this program, we will read the name of the non-empty directory, and then we will remove the given non-empty directory using the system() function by specifying the "rm" command.

Remove a non-empty directory using the system() function in C

The source code to remove a non-empty directory is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to remove a non-empty directory
// using the system() command

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

int main()
{
    char dirName[16];
    char cmd[32] = { 0 };

    int ret = 0;

    printf("Enter directory name: ");
    scanf("%s", dirName);

    sprintf(cmd, "rm -rf %s", dirName);

    ret = system(cmd);

    if (ret == 0)
        printf("Given non-empty directory deleted successfully\n");
    else
        printf("Unable to delete directory %s\n", dirName);

    return 0;
}

Output

Enter directory name: image
Given non-empty directory deleted successfully

Explanation

Here, we created a character array dirName. Then we read the name of the directory from the user. Then we removed the non-empty directory using the system() function. The system() function is used to execute the command. So, we created a command using the sprintf() function. Then we pass the created command in the system() function and removed the given non-empty directory. After that, we printed the appropriate message on the console screen.

C File Handling Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.