Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

10.10. Creating a Directory

Problem

You have to create 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 mkdir system call that is shipped with most compilers as part of the C headers. It takes on different forms in different OSs, but regardless, you can use it to create a new directory. There is no standard C++, portable way to create a directory. Check out Example 10-15 to see how.

Example 10-15. Creating a directory

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

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

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

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

Discussion

The system call for creating directories differs somewhat from one OS to another, but don’t let that stop you from using it anyway. Variations of mkdir are supported on most systems, so creating a directory is just a matter of knowing which header to include and what the function’s signature looks like.

Example 10-15 works on Windows, but not Unix. On Windows, mkdir is declared in <direct.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.

On Unix, mkdir is declared in <sys/stat.h>, and its signature is slightly different. The ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page