폴더안에있는 파일 이름 벡터에 저장하기

DONGJE LEE·2023년 4월 14일
0

C++

목록 보기
8/12
post-thumbnail
#include <dirent.h>
#include <string>

int main()
{
	DIR *dir;
    struct dirent *ent;

    // 폴더 경로
    std::string folder_path = "/home/***";

    // 파일 이름을 저장할 벡터
    std::vector<std::string> file_names;

    // 폴더 열기
    if ((dir = opendir(folder_path.c_str())) != NULL) {
        // 폴더 안에 있는 모든 파일 읽기
        while ((ent = readdir(dir)) != NULL) {
            // 파일 이름 출력
            std::cout << ent->d_name << std::endl;
            file_names.push_back(ent->d_name);
        }

        // 폴더 닫기
        closedir(dir);
    } else {
        // 폴더 열기 실패
        std::cerr << "Failed to open directory" << std::endl;
        return -1;
    }

    // 파일 이름을 알파벳 순서로 정렬
    std::sort(file_names.begin(), file_names.end());

    // 정렬된 파일 이름 출력
    for (const auto& name : file_names) {
        std::cout << name << std::endl;
    }


    return 0;

}
profile
LiDAR & SLAM & Robotics & Autonomous System

0개의 댓글