Home

How to Delete a Directory in C++

|
Updated:  
2016-03-26 08:29:48
|
From The Book:  
C++ Essentials For Dummies
Explore Book
Buy On Amazon

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.

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.