YOGYUI

C++::디렉터리 존재 여부 확인하기 (g++) 본문

Software/C, C++

C++::디렉터리 존재 여부 확인하기 (g++)

요겨 2022. 7. 25. 19:32
반응형

C++: Check Directory Existence (g++)

 

#include <sys/stat.h>

bool check_dir_exist(const char *path) {
    bool exist = false;
    struct stat st;
    if(stat(path, &st) == 0) {
        if( ((st.st_mode) & S_IFMT) == S_IFDIR ) {
            exist = true;
        }
    }

    return exist;
}

헤더파일 <sys/stat.h>를 include한 뒤 stat 함수 호출

 int stat(const char *path, struct stat *buf);

path: 경로명 문자열 포인터 (입력)
buf: 경로에 대한 정보가 담긴 stat 구조체 (출력)

리턴값: 0 = 성공, -1 = 실패 (실패 이유는 다양하며, errno 전역변수로 확인)

stat 구조체 내에 경로(파일 혹은 디렉터리 등)의 정보를 담고 있는 변수를 참조할 수 있다

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* 파일의 종류 및 접근권한 */
    nlink_t   st_nlink;   /* hardlink 된 횟수 */
    uid_t     st_uid;     /* 파일의 owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* 파일의 크기(bytes) */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

경로의 유형은 4가지로, 16비트 정수의 최상위 4bit로 정의되어 있다

#define S_IFMT 0xF000

#define S_IFIFO 0x1000  // FIFO
#define S_IFCHR 0x2000  // Character Device
#define S_IFDIR 0x4000  // Directory
#define S_IFREG 0x8000  // Regular File

따라서 경로가 디렉터리인지 여부는 비트연산을 통해 쉽게 판별할 수 있다

(st.st_mode) & S_IFMT) == S_IFDIR;

※ S_IFDIR을 S_IFREG로 바꾸면 파일인지 여부를 확인할 수 있다

 

바로 테스트해보자

#include <string>
#include <iostream>

int main(int argc, char *argv[]) {
    std::string path1("./test_dir_1");
    std::string path2("./test_dir_2");

    if (check_dir_exist(path1.c_str())) {
        std::cout << "Path1 (" << path1 << ") Exist\n";
    } else {
        std::cout << "Path1 (" << path1 << ") Not Exist\n";
    }

    if (check_dir_exist(path2.c_str())) {
        std::cout << "Path2 (" << path2 << ") Exist\n";
    } else {
        std::cout << "Path2 (" << path2 << ") Not Exist\n";
    }

    return 0;
}
g++ -g main.cpp -o main

테스트를 위해 빌드 결과 디렉터리에 "test_dir_1" 경로만 생성해줬다 (mkdir)

-- src
---- test_dir_1
---- main.cpp
---- main

windows
ununtu
macOS

 

[Git repo]

https://github.com/YOGYUI/Sniffets/tree/main/posix_check_dir_exist

 

GitHub - YOGYUI/Sniffets: 간단한 예제 코드들

간단한 예제 코드들. Contribute to YOGYUI/Sniffets development by creating an account on GitHub.

github.com

 

[참조]

https://stackoverflow.com/questions/4980815/c-determining-if-directory-not-a-file-exists-in-linux

https://www.it-note.kr/173

https://www.ibm.com/docs/en/i/7.1?topic=ssw_ibm_i_71/apis/stat.htm

 

 

반응형
Comments