×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to remove an empty directory

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

Problem statement

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

C program to remove an empty directory

The source code to remove an empty directory using the system() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

//C program to remove an empty directory
// using the system() function

#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, "rmdir %s", dirName);

    ret = system(cmd);

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

    return 0;
}

Output

RUN 1:
Enter directory name: empty
Given Empty directory deleted successfully

RUN 2:
Enter directory name: hello
rmdir: failed to remove ‘hello’: No such file or directory
Unable to delete directory hello

Explanation

Here, we created a character array dirName. Then we read the name of the directory from the user. And, we removed the empty directory using the system() function. The system() function is used to execute the command. Here we created a command using the sprintf() function. Then we pass the created command in the system() function and removed the given 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.