C++ All-in-One For Dummies
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:

#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 Mueller has produced 114 books and more than 600 articles on topics ranging from functional programming techniques to working with Amazon Web Services (AWS). Luca Massaron, a Google Developer Expert (GDE),??interprets big data and transforms it into smart data through simple and effective data mining and machine learning techniques.

This article can be found in the category: