如果目录不存在,请创建该目录

Create a directory if it doesn't exist

本文关键字:创建 不存在 如果      更新时间:2023-10-16

在我的应用程序中,我想将文件复制到另一个硬盘,所以这是我的代码:

 #include <windows.h>
using namespace std;
int main(int argc, char* argv[] )
{
    string Input = "C:\Emploi NAm.docx";
    string CopiedFile = "Emploi NAm.docx";
    string OutputFolder = "D:\test";
    CopyFile(Input.c_str(), string(OutputFolder+CopiedFile).c_str(), TRUE);
    return 0;
}

所以在执行完这个之后,它在D: HDD中向我显示了一个文件testEmploi NAm.docx但如果测试文件夹不存在,我希望他创建它。

我想在不使用Boost库的情况下做到这一点。

使用WINAPI CreateDirectory()函数创建文件夹。

您可以在不检查目录是否已经存在的情况下使用此功能,因为它将失败,但GetLastError()将返回ERROR_ALREADY_EXISTS:

if (CreateDirectory(OutputFolder.c_str(), NULL) ||
    ERROR_ALREADY_EXISTS == GetLastError())
{
    // CopyFile(...)
}
else
{
     // Failed to create directory.
}

构建目标文件的代码不正确:

string(OutputFolder+CopiedFile).c_str()

这将产生"D:testEmploi Nam.docx":目录和文件名之间缺少路径分隔符。修复示例:

string(OutputFolder+"\"+CopiedFile).c_str()
#include <experimental/filesystem> // or #include <filesystem> for C++17 and up
    
namespace fs = std::experimental::filesystem;

if (!fs::is_directory("src") || !fs::exists("src")) { // Check if src folder exists
    fs::create_directory("src"); // create src folder
}

可能最简单、最高效的方法是使用boost和boost::文件系统函数。通过这种方式,您可以简单地构建一个目录,并确保它与平台无关。

const char* path = _filePath.c_str();
boost::filesystem::path dir(path);
if(boost::filesystem::create_directory(dir))
{
    std::cerr<< "Directory Created: "<<_filePath<<std::endl;
}

boost::filesystem::create_directory-文档

以下是创建文件夹的简单方法。。。。。。。

#include <windows.h>
#include <stdio.h>
void CreateFolder(const char * path)
{   
    if(!CreateDirectory(path ,NULL))
    {
        return;
    }
}

CreateFolder("C:\folder_name\")

上面的代码对我来说效果很好。

_mkdir也将执行此任务。

_mkdir("D:\test");

https://msdn.microsoft.com/en-us/library/2fkk4dzw.aspx

由于c++17,您可以使用轻松完成跨平台操作

#include <filesystem>
int main() {
bool created_new_directory = false;
bool there_was_an_exception = false;
try {
  created_new_directory
      = std::filesystem::create_directory("directory_name");
} catch(std::exception & e){
there_was_an_exception = true;
// creation failed
}
if ((not created_new_directory) and (not there_was_an_exception)) {
    // no failure, but the directory was already present.
  }
}

注意,如果您需要知道目录是否真的是新创建的,这个版本非常有用。在这一点上,我发现关于cppreference的文档有点难以理解:如果目录已经存在,则此函数返回false。

这意味着,您可以使用此方法或多或少地以原子方式创建一个新目录。

OpenCV特定

Opencv支持文件系统,可能是通过它的依赖Boost。

#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);

使用CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

如果函数成功,则返回非零,否则返回NULL

这适用于GCC:

取自:在C 中创建新目录

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat st = {0};
if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

您可以使用cstdlib

尽管——http://www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>
const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}

您也可以使用检查目录是否已经存在

#include <dirent.h>