×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to remove an empty directory using rmdir() function

Here, we are going to learn how to remove an empty directory using rmdir() function using C program?
Submitted by Nidhi, on August 14, 2021

Problem statement

Input the name of the directory (path) and then remove the given empty directory using the rmdir() function.

Removing an empty directory using rmdir() function

The rmdir() function is a library function of <sys/types.h> header file which is used to remove an empty directory, the directory must not contain any files or directories.

Syntax

int rmdir( const char* path );

The argument path is the path of the directory that you want to delete.

The function returns 0 if the directory is removed successfully, it returns -1 if the directory is the current working directory of any process, If the directory is the root directory, the effect of this function depends on the filesystem.

C program to remove an empty directory using rmdir() function

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

// C program to remove empty directory
// using rmdir() function

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main()
{
    char dirName[16];
    int ret = 0;

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

    ret = rmdir(dirName);

    if (ret == 0)
        printf("Given empty directory removed successfully\n");
    else
        printf("Unable to remove directory %s\n", dirName);

    return 0;
}

Output

Enter directory name: newDir
Directory created successfully

Explanation

Here, we created a character array dirName. Then we read the name of the directory from the user. Then we removed the given directory using the rmdir() function and 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.