We want to create a file which path looks like /Folder1/Folder2/Folder3/file.txt. The parent directory Folder3 of file.txt has to be there, or the creating action will fail. Similarly, Folder2 and Folder1 need to be on the disk firstly. If you are a Linux OS user, you can use the following command line to create folders.
mkdir -p /Folder1/Folder2/Folder3
Now the post introduces how to create these parent directories in CPlusPlus program.
#include <iostream>
#include <sys/stat.h>
#include <errno.h>
bool CreateDirForFilePath(const std::string& path)
{
size_t pos = 0, found;
found = path.find_last_of( '/', std::string::npos );
if( found != std::string::npos )
{
std::string folder = path.substr( 0, found );
if( folder.empty() == false )
{
LOG( INFO, "found folder: ", folder );
return CreateDirectories( folder );
}
}
return true;
}
bool CreateDirectories(const std::string& path)
{
size_t current = 0, found;
while ((found = path.find_first_of('/', current)) != std::string::npos) {
std::string sub_path = path.substr(0, found++);
current = found;
if (sub_path.empty()) continue;
if (!CreateDirectory(sub_path)) {
return false;
}
}
return CreateDirectory(path);
}
bool CreateDirectory(const std::string& path)
{
int status = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (status == 0) {
LOG( INFO, "created dir: ", path );
return true;
} else {
if (errno == EEXIST) {
return true;
} else {
LOG( ERR, "failed to create dir: ", path, ", ", strerror(errno) );
return false;
}
}
}
The interface CreateDirForFilePath will find the directory prefix and create neccessary folders. These code can be compiled on Linux OS.