Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

File Handling Examples Programs in C language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to check a given filename is a directory... >>
<< C program to remove an empty directory...