C 폴더 생성 – 계층 구조의 폴더 생성

이글에서는 C 언어로 계층 구조로 되어 있는 폴더명을 한번에 만드는 소스코드를 보여드립니다.
그 과정을 위하여 중요 함수도 소개해 드립니다. – C 폴더 생성 –

소개

C 언어에서 계층 구조의 폴더를 만드려면 순서대로 폴더를 만들어야 합니다.
즉 C:\firstfolder\secondfolder 의 폴더를 만들려면 먼저 C:\firstfolder 를 만들고 C:\firstfolder\secondfolder 이렇게 두번의 폴더를 만들어야 합니다.
이런 여러번의 작업을 한번에 할 수 있는 함수를 만들어 소개해 드립니다.
이 코드는 리눅스, 윈도우즈 모두 사용 할 수 있는 코드입니다.

핵심 함수

리눅스를 위한 mkdir

“mkdir”은 C 언어에서 디렉토리를 만드는 함수입니다. 이 함수를 사용하면 프로그램에서 새로운 디렉토리를 만들 수 있습니다. 보통 파일 시스템 내에서 작업할 때 새로운 디렉토리를 만들어야 할 때가 많은데, 이때 “mkdir” 함수를 사용하면 편리합니다.

“mkdir” 함수는 <sys/stat.h> 헤더 파일에 선언되어 있습니다. 사용 방법은 간단합니다. 다음은 “mkdir” 함수의 기본적인 형식입니다:

#include <sys/stat.h>
#include <sys/types.h>

int mkdir(const char *pathname, mode_t mode);
  • pathname: 생성할 디렉토리의 경로를 나타내는 문자열입니다.
  • mode: 새로운 디렉토리의 퍼미션을 나타내는 부분입니다. 보통은 0777과 같이 8진수로 표현됩니다. 이 부분을 0으로 두면 기본 퍼미션을 사용하게 됩니다.

예를 들어, 다음은 “example_directory”라는 디렉토리를 현재 작업 디렉토리에 만드는 예제 코드입니다:

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

int main() {
    const char *path = "example_directory";
    int status = mkdir(path, 0777);

    if (status == 0) {
        printf("디렉토리 생성 성공\n");
    } else {
        printf("디렉토리 생성 실패\n");
    }

    return 0;
}

Windows 를 위한 CreateDirectory

“CreateDirectory” 함수는 Windows 플랫폼에서 디렉토리를 만드는 데 사용되는 함수입니다. 이 함수는 C 언어에서 Windows API를 활용하여 디렉토리를 생성할 때 유용합니다.

“CreateDirectory” 함수는 <windows.h> 헤더 파일에 선언되어 있습니다. 이 함수의 기본 형식은 다음과 같습니다:

#include <windows.h>

BOOL CreateDirectoryA(
  LPCSTR                lpPathName,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
  • lpPathName: 생성할 디렉토리의 경로를 나타내는 문자열입니다.
  • lpSecurityAttributes: 디렉토리의 보안 특성을 지정하는데 사용되는 포인터입니다. 보안 특성을 변경할 필요가 없다면 NULL을 전달하면 됩니다.

예를 들어, 다음은 “example_directory”라는 디렉토리를 생성하는 예제 코드입니다:

#include <stdio.h>
#include <windows.h>

int main() {
    LPCSTR path = "example_directory";
    BOOL result = CreateDirectoryA(path, NULL);

    if (result) {
        printf("디렉토리 생성 성공\n");
    } else {
        printf("디렉토리 생성 실패\n");
    }

    return 0;
}

계층 구조의 폴더 생성 코드

다음은 계층 구조로 되어 있는 폴더구조를 모두 만드는 예제 코드 입니다.

#define _CRT_NONSTDC_NO_DEPRECATE

#include<stdio.h>
#include<stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#if defined (WIN32)
#include <windows.h>
#endif

int
mkdirHierarchy (const char *pathname, unsigned short mode)
{
    struct stat     sbuf;
    char           *ourcopy = strdup(pathname);
    char           *entry;
    char           *buf = NULL;
    char           *st = NULL;
    int             res;

    res = -1;
    if (!ourcopy)
        goto out;

    buf = (char *)malloc(strlen(pathname) + 2);
    if (!buf)
        goto out;

#if defined (WIN32) || defined (cygwin)
    /* 리눅스를 위해 백슬래쉬를 슬레쉬로 교체 */
    for (entry = ourcopy; *entry; entry++)
        if (*entry == '\\')
            *entry = '/';
#endif

    entry = strtok(ourcopy, "/");

    buf[0] = '\0';

#if defined (WIN32) || defined (cygwin)
    /*
     * 드라이브가 포함되어 있다면 
     *   e.g  "c:/path"
     */
    if ((entry) && (':' == entry[1]) &&
        (('\0' == entry[2]) || ('/' == entry[2])))
    {
        strcat(buf, entry);
        entry = strtok(NULL, "/");
    }
#endif

    /*
     * 파일네임이 폴더인지를 체크한다.
     */
    while (entry)
    {
        strcat(buf, "/");
        strcat(buf, entry);
        entry = strtok(NULL, "/");

        if (stat(buf, &sbuf) < 0)
        {

#ifdef WIN32
            if (CreateDirectory(buf, NULL) == 0)
#else
            if (mkdir(buf, mode) == -1)
#endif
                goto out;
            else
                printf("Created directory: %s\n", buf);
        }
        else
        {
            /*
             * 이미존재
             */
            if ((sbuf.st_mode & S_IFDIR) == 0)
            {
                /*
                 * 파일이 존재하므로 만들수 없음
                 */
                goto out;
            }
        }
    }
    res = 0;
out:
    free(buf);
    free(ourcopy);
    return res;
}

int main()
{
#if defined (WIN32)
    mkdirHierarchy ("D:\\firstfolder\\secondfolder", 0);
#else
    mkdirHierarchy ("/home/root/firstfolder/secondfolder", 755);
#endif

    return 0;
}

위코드는 여러단계의 폴더구조를 한번에 만들수 있는 소스 코드입니다.
mkdirHierarchy 함수를 이용해서 한번에 만들 수 있습니다.

결론

C 언어에서 계층구조의 디렉토리를 생성하는 방법에 대해 알아보았습니다. 디렉토리 생성은 파일 시스템을 효율적으로 관리하고 데이터를 구조화하는 데 중요한 요소입니다.

Leave a Comment