[MFC] 폴더 생성 및 파일 생성[MFC] 폴더 생성 및 파일 생성

Posted at 2009. 1. 1. 02:59 | Posted in 프로그래밍 언어/C/C++/MFC
1. 폴더 생성

CreateDirectory(_T("main"), NULL);
CreateDirectory(_T("main/sub1"), NULL);

첫번째 인자는 만들 디렉토리 이름, 두 번째 인자는 security 설정인데 패스;
CreateDirectory 함수는 MFC로 프로젝트를 만들면 기본적으로 사용할 수 있는 함수이다.
main/sub 식으로 만들기 위해선 main 디렉토리를 만든 이후 main/sub 디렉토리를 만들어야 한다.

만약 아무 디렉토리도 없는 상태에서 main/sub/subsub 를 만들고자 한다면 다음과 같이 할 수 있다.
void CreateFolder(CString csPath)
{
    // UpdateData(TRUE);
    // csPath = m_csTopFolderName + csPath;

    CString csPrefix(_T("")), csToken(_T(""));
    int nStart = 0, nEnd;
    while( (nEnd = csPath.Find('/', nStart)) >= 0)
    {
        CString csToken = csPath.Mid(nStart, nEnd-nStart);
        CreateDirectory
(csPrefix + csToken, NULL);

        csPrefix += csToken;
        csPrefix += _T("/");
        nStart = nEnd+1;
    }
    csToken = csPath.Mid(nStart);
    CreateDirectory(csPrefix + csToken, NULL);
}

CreateFolder(_T("main/sub/subsub"));식으로 호출하면 된다.

while 문에서 / 단위로 끊어 읽으면서 디렉토리를 생성한다.
while 문 안에서 main, main/sub 디렉토리가 생성되며
while 문 밖에서 main/sub/subsub 디렉토리가 생성된다.

여기서 무작정 CreateDirectory를 호출하지 않고 csToken 값에 . 이 있는지를 검사한다.
. 이 포함되어 있다면 파일이므로 CreateDirectory가 아닌 CFile 등의 방법으로 파일을 만들도록 코드를 수정하면
CreateFolder(_T("main/sub/subsub.cpp"));식으로도 사용할 수 있을 것이다
아래 박스 코드를 위 코드의 CreateDirectory(...) 대신 쓰면 된다.

if(csToken.Find('.') >= 0)
    CreateFile(csToken, csPrefix);
else
    CreateDirectory(csPrefix + csToken, NULL);

물론, 폴더 이름에 . 을 넣거나 하면 낭패다-_-;

2. 파일 생성

파일이 존재하지 않으면 기본적인 내용을 추가하여 파일을 생성하고, 존재하면 건너뛰는 코드이다.

void CreateFile(CString csFileName, CString csPrefix)
{
    CFile file;
    if(!file.Open(csPrefix + csFileName, CFile::modeRead))
    {
        file.Open(csPrefix + csFileName, CFile::modeCreate|CFile::modeWrite);
        file.Write(~~~~);
    }
    file.Close();
}


사실, 파일이 존재하면 그 파일 내용을 지우지 않고 여는 방법은 단순하다.

CFile file(_T("main.cpp"), CFile::modeCreate|CFile::modeNoTruncate);

하지만 파일이 존재하면 아무 일도 하지 않고,
파일이 존재하지 않을 때 파일을 생성 및 기본적인 내용을 추가하려 한다면
modeNoTruncate 로 여는 것으론 해결할 수 없다.

예 >> a.cpp 파일을 생성하는데 파일이 없으면 int main(){ return 0; } 을 넣어 생성하고,  
    >> 파일이 있다면 아무 일도 수행하지 않으려 하는 경우.
    >> 기껏 a.cpp 코딩 다 해 놨는데 이 파일을 위와 같은 초기화 파일로 만들면 슬퍼지니까;;;


//