본문 바로가기
IT/programming

[C/C++] readdir을 활용한 파일 목록 읽기 예제, 파일 탐색기

by 어느해겨울 2022. 1. 7.

readdir을 활용한 파일 목록 읽기 예제, 파일 탐색기

C언어에서 readdir 함수를 사용하는 재귀 함수로 구성하였다.

디렉터리는 제외하고 파일만 조회하고 탐색된 전체 경로(full path)를 글로벌 vector에 저장한다.

 

이전 포스팅 중 PHP로 구현한 파일 탐색기와 동일한 기능을 수행한다.

https://muabow.tistory.com/249

 

[PHP] readdir을 활용한 파일 목록 읽기 예제, 파일 탐색기

readdir을 활용한 파일 목록 읽기 예제, 파일 탐색기 opendir, readdir, is_dir 함수를 사용하는 재귀 함수로 구성하였다. 디렉터리는 제외하고 파일만 조회하고 탐색된 전체 경로(full path)를 배열로 반환

muabow.tistory.com

 

소스코드

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

#include <iostream>
#include <vector>
#include <string>

using namespace std;

// global variables
vector<string> v_file_list;


// function
bool get_file_list(string _target_dir, int _depth = 0) {
    string  str_current_path;
    string  str_full_path;

    DIR     *fp = NULL;
    struct dirent *entry;

    if( (fp = opendir(_target_dir.c_str())) == NULL ) {
        fprintf(stderr, "get_file_list() couldn't open directory : %s\n", _target_dir.c_str());
        return false;
    }

    while( (entry = readdir(fp)) != NULL ) {
        if( strcmp(entry->d_name, "..") != 0 && strcmp(entry->d_name, ".") != 0 ) {
            if( entry->d_type == DT_DIR ) {
                str_current_path = _target_dir;
                str_current_path.append("/").append(entry->d_name);
                if( !get_file_list(str_current_path, _depth + 1) ) return false;

            } else {
                str_full_path = _target_dir;
                str_full_path.append("/").append(entry->d_name);
                if( str_full_path.find(".") == string::npos ) continue;

                v_file_list.push_back(str_full_path);
            }
        }
    }

    closedir(fp);

    return true;
}

int main(int _argc, char* _argv[]) {
    get_file_list("/var/log/apache2");

    for( int idx = 0 ; idx < (int)v_file_list.size() ; idx++ ) {
        printf("%s\n", v_file_list[idx].c_str());
    }

    return 0;
}

 

결과

$ g++ get_file_list.cpp -o get_file_list --std=c++11 ; ./get_file_list

/var/log/apache2/access.log.1
/var/log/apache2/access.log
/var/log/apache2/error.log.11.gz
/var/log/apache2/access.log.3.gz
/var/log/apache2/access.log.6.gz
/var/log/apache2/access.log.12.gz
/var/log/apache2/access.log.5.gz
/var/log/apache2/access.log.9.gz
/var/log/apache2/access.log.11.gz
/var/log/apache2/error.log.4.gz
/var/log/apache2/error.log.3.gz
/var/log/apache2/error.log.10.gz
/var/log/apache2/error.log.6.gz
/var/log/apache2/other_vhosts_access.log
/var/log/apache2/error.log
/var/log/apache2/access.log.8.gz
/var/log/apache2/error.log.8.gz
/var/log/apache2/access.log.10.gz
/var/log/apache2/error.log.14.gz
/var/log/apache2/error.log.7.gz
/var/log/apache2/error.log.13.gz
/var/log/apache2/error.log.1
/var/log/apache2/access.log.7.gz
/var/log/apache2/access.log.14.gz
/var/log/apache2/access.log.4.gz
/var/log/apache2/error.log.5.gz
/var/log/apache2/error.log.2.gz
/var/log/apache2/error.log.9.gz
/var/log/apache2/access.log.2.gz
/var/log/apache2/access.log.13.gz
/var/log/apache2/error.log.12.gz

해당 함수는 파일 탐색 시 전체 경로를 vector로 반환하기 때문에 파일을 제어해야 하는 상황에 유용하게 사용된다.

추후에 글로벌 영역이 아닌 로컬에서 자기완결적으로 끝내는 함수로 수정하겠다.

 

끝.

 

 

 

댓글