Nice programing

존재하지 않는 경우 디렉토리 생성

nicepro 2021. 1. 9. 11:39
반응형

존재하지 않는 경우 디렉토리 생성


내 앱에서 파일을 다른 하드 디스크에 복사하고 싶습니다. 이것이 내 코드입니다.

 #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()

아마도 가장 쉽고 효율적인 방법은 boost와 boost :: filesystem 함수를 사용하는 것입니다. 이렇게하면 디렉토리를 간단하게 구축하고 플랫폼 독립적인지 확인할 수 있습니다.

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 <experimental/filesystem> // or #include <filesystem>

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
}

다음은 폴더를 만드는 간단한 방법입니다 .......

#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


사용하다 CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

함수가 성공하면 0이 아닌 값을 반환 NULL합니다.


OpenCV 특정

Opencv는 아마도 의존성 부스트를 통해 파일 시스템을 지원합니다.

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

cstdlib 를 사용할 수 있습니다.

비록-http: //www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>

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

다음을 사용하여 디렉토리가 이미 존재하는지 확인할 수도 있습니다.

#include <dirent.h>

참조 URL : https://stackoverflow.com/questions/9235679/create-a-directory-if-it-doesnt-exist

반응형