10.11. Removing a Directory

Problem

You need to remove a directory, and you want to do it portably, i.e., without using OS-specific APIs.

Solution

On most platforms, you will be able to use the rmdir system call that is shipped with most compilers as part of the C headers. There is no standard C++, portable way to remove a directory. rmdir takes on different forms in different OSs, but regardless, you can use it to remove a directory. See Example 10-17 for a short program that removes a directory.

Example 10-17. Removing a directory

#include <iostream>
#include <direct.h>

using namespace std;

int main(int argc, char** argv) {

   if (argc < 2) {
      cerr << "Usage: " << argv[0] << " [dir name]" << endl;
      return(EXIT_FAILURE);
   }

   if (rmdir(argv[1]) == -1) {  // Remove the directory
      cerr << "Error: " << strerror(errno) << endl;;
      return(EXIT_FAILURE);
   }
}

Discussion

The signature of rmdir is the same on most OSs, but the header file where it is declared is not. On Windows, it is declared in <direct.h>, and on Unix, it is declared in <unistd.h>. It takes one parameter (the directory name), returns -1 if there is an error, and sets errno to the corresponding error number. You can get the implementation-defined error text by calling strerror or perror.

If the target directory is not empty rmdir will return an error. To list the contents of a directory, to enumerate them for deletion, etc., see Recipe 10.12.

If you want portability, and don’t want to write a bunch of #ifdefs around the various OS-specific ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.