C++: manipulating directories

De Wiki de Calcul Québec
Aller à : Navigation, rechercher
Cette page est une traduction de la page C++ : manipulation de répertoires et la traduction est complétée à 100 % et à jour.

Autres langues :anglais 100% • ‎français 100%

In C++, using <fstream> to read and write files is well known and amply documented. However, what about directories? How can we detect the presence of a directory and create a new one? Reference manuals do not say much regarding this subject.

Directory manipulation can be done using the POSIX header files <dirent.h> and <sys/stat.h>, as shown in the below code:

File : directory.cpp
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
 
//
// Returns whether the specified directory exists.
//
// Example:
// --------
//          if (!directoryExists("output"))
//          {
//              createDirectory("output");
//          }
// --------------------------------------------------------
bool directoryExists(const char* dir)
{
    DIR* dhandle = opendir(dir);
 
    if (dhandle != NULL)
    {
        closedir(dhandle);
        return true;
    }
    else
    {
        return false;
    }
}
 
//
// Creates the specified directory. Fails if the path leading to
// this directory does not exist.
//
// Example:
// --------
//          createDirectory("output");
// --------------------------------------------------------
bool createDirectory(const char* dir)
{
    return mkdir(dir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0;
}
 
//
// Creates a complete path.
//
// Example:
// --------
//          createPath("output/sample1/temperature0/");
// --------------------------------------------------------
bool createPath(const char* path)
{
    char localpath[256];
    strcpy(localpath, path);
 
    char directory[256];
    if (path[0] == '/')
    {
        strcpy(directory, "/");
    }
    else
    {
        strcpy(directory, "");
    }
 
    char* pch = strtok(localpath, "/");
    while (pch != NULL)
    {
        strcat(directory, pch);
        strcat(directory, "/");
        if (!directoryExists(directory) && !createDirectory(directory))
        {
            return false;
        }
 
        pch = strtok(NULL, "/");
    }
 
    return true;
}


Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Ressources de Calcul Québec
Outils
Partager