Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Recursive Directory Deletion in C on Linux

Tech Nov 29 10

Background

The standard rmdir() system call only removes directories that contain no files or subdirectories. To delete a non-empty directory, you need to implement recursive traversal that removes contents before removing the directory itself.

How rm -rf Operates

When the shell executes rm -rf <directory>, it follows a specific pattern:

  1. Opens the target directory
  2. Iterates through all entry (files and subdirectories)
  3. For subdirectories, recursively applies the same deletion logic
  4. For files, deletes them directly using unlinkat()
  5. After all contents are removed, deletes the now-empty directory

Example Directory Structure

# tree dir_test/
dir_test/
├── 3.txt
├── 4.txt
├── 5.txt
└── dir1
    ├── 1.txt
    └── 2.txt

1 directory, 5 files

System Call Trace Analysis

Using strace to trace rm -rf dir_test/ reveals the underlying system calls:

execve("/usr/bin/rm", ["rm", "-rf", "dir_test/"], ...) = 0
newfstatat(AT_FDCWD, "dir_test/", ..., AT_SYMLINK_NOFOLLOW) = 0
openat(AT_FDCWD, "dir_test/", O_RDONLY|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW|O_DIRECTORY) = 3
openat(4, "dir1", ..., O_DIRECTORY) = 3
unlinkat(5, "1.txt", 0)                 = 0
unlinkat(5, "2.txt", 0)                 = 0
unlinkat(4, "dir1", AT_REMOVEDIR)       = 0
unlinkat(4, "3.txt", 0)                 = 0
unlinkat(4, "4.txt", 0)                 = 0
unlinkat(4, "5.txt", 0)                 = 0
unlinkat(AT_FDCWD, "dir_test/", AT_REMOVEDIR) = 0

The sequence shows files being deleted first (unlinkat with flag 0), followed by directory removal (unlinkat with AT_REMOVEDIR).

Implementation

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <limits.h>

void purgeRecursive(const char* targetPath) {
    struct stat status;
    
    if (lstat(targetPath, &status) < 0) {
        perror("lstat");
        return;
    }

    if (S_ISDIR(status.st_mode)) {
        DIR* dp = opendir(targetPath);
        if (dp == NULL) {
            perror("opendir");
            return;
        }

        char fullPath[PATH_MAX];
        struct dirent* entry;
        
        while ((entry = readdir(dp)) != NULL) {
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
                continue;
            }

            snprintf(fullPath, sizeof(fullPath), "%s/%s", targetPath, entry->d_name);
            purgeRecursive(fullPath);
        }

        closedir(dp);

        if (rmdir(targetPath) < 0) {
            perror("rmdir");
            return;
        }

        printf("Removed directory: %s\n", targetPath);
    } else if (S_ISREG(status.st_mode)) {
        if (remove(targetPath) < 0) {
            perror("remove");
            return;
        }
        printf("Removed file: %s\n", targetPath);
    } else {
        fprintf(stderr, "%s: unsupported file type\n", targetPath);
    }
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <target_path>\n", argv[0]);
        return 1;
    }

    purgeRecursive(argv[1]);
    return 0;
}

Execution Results

# ./a.out dir_test/
Removed file: dir_test//dir1/1.txt
Removed file: dir_test//dir1/2.txt
Removed directory: dir_test//dir1
Removed file: dir_test//3.txt
Removed file: dir_test//4.txt
Removed file: dir_test//5.txt
Removed directory: dir_test/

The output matches the rm -rf system call sequence exactly, confirming the implementation correctly handles recursive directory deletion by processing files before attempting to remove their parenet directories.

Tags: Linux

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.