How to Delete a Directory in C++ - dummies

By John Paul Mueller, Jeff Cogswell

It’s fun to go on a cleaning spree and just toss everything out. And so it makes sense that deleting a directory is easy. To do it, you just call the rmdir function, passing the name of the directory. If you want to find out whether it worked, test its results against 0. Here’s some sample code:

#include <iostream>
#include <stdio.h>
#include <io.h>
using namespace std;
int main()
{
    if (rmdir("../abc") != 0)
    {
        cout << "Life is difficult sometimes, and" << endl;
        cout << "sometimes you just don't get what" << endl;
        cout << "you asked for. And this is one" << endl;
        cout << "such case. I just couldn't remove" << endl;
        cout << "the directory for you. Better" << endl;
        cout << "luck next time, my dear friend." << endl;
    }
    return 0;
}

Make sure you verify that the directory is added and removed as expected.

This approach works only if the directory is not empty. If the directory has at least one file in it, the function can’t remove the directory — and returns a nonzero result. Then you get to see the nice, friendly message that we’re particularly proud of.