C++ All-in-One For Dummies, 4th Edition
Book image
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:

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 has written more than 100 books and more than 600 articles on topics ranging from functional programming techniques to application development using C++.

This article can be found in the category: