본문 바로가기

Programming language/C++

[C++] 간편 파일 탐색기

안녕하세요 오늘은 간편 파일 탐색기입니다.

C++로 파일 탐색기를 만들려면 Windows 애플리케이션용 Windows API 또는 Qt와 같은 크로스 플랫폼 라이브러리와 같은 GUI 개발을 위한 플랫폼별 라이브러리를 사용해야 합니다. 아래는 현재 디렉터리에 있는 파일과 디렉터리를 나열하고 탐색할 수 있는 간소화된 콘솔 기반 파일 탐색기입니다.

 

소스코드

#include <iostream>
#include <filesystem>
#include <string>
using namespace std;
namespace fs = std::filesystem;

void listFiles(const string& path) {
    try {
        for (const auto& entry : fs::directory_iterator(path)) {
            if (fs::is_directory(entry)) {
                cout << "[D] " << entry.path().filename() << endl;
            } else if (fs::is_regular_file(entry)) {
                cout << "[F] " << entry.path().filename() << endl;
            }
        }
    } catch (const fs::filesystem_error& e) {
        cerr << "Error: " << e.what() << endl;
    }
}

int main() {
    string currentPath = fs::current_path().string();
    char choice;

    cout << "Simple File Explorer" << endl;

    do {
        cout << "\nCurrent Directory: " << currentPath << endl;
        listFiles(currentPath);

        cout << "\nOptions:" << endl;
        cout << "1. Enter a directory" << endl;
        cout << "2. Go up one level" << endl;
        cout << "3. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case '1':
                cout << "Enter the directory name: ";
                string newDir;
                cin >> newDir;
                currentPath = fs::canonical(currentPath + "/" + newDir).string();
                break;
            case '2':
                currentPath = fs::canonical(currentPath + "/..").string();
                break;
            case '3':
                break;
            default:
                cout << "Invalid choice. Try again." << endl;
        }

    } while (choice != '3');

    return 0;
}

이 코드는 콘솔에서 간단한 파일 탐색기를 제공합니다. 이 코드를 사용하면 디렉터리를 탐색하고, 파일과 하위 디렉터리를 나열하고, 프로그램을 종료할 수 있습니다. 이 기반을 확장하여 더 풍부한 기능을 갖춘 파일 탐색기를 만들거나 사용자 친화적인 인터페이스를 위해 GUI 라이브러리 사용을 고려할 수 있습니다.

 

출력 결과

Simple File Explorer

Current Directory: /path/to/your/current/directory
[D] Subdirectory1
[F] File1.txt
[F] File2.txt

Options:
1. Enter a directory
2. Go up one level
3. Exit
Enter your choice: 1
Enter the directory name: Subdirectory1

Current Directory: /path/to/your/current/directory/Subdirectory1
[F] SubFile1.txt
[F] SubFile2.txt

Options:
1. Enter a directory
2. Go up one level
3. Exit
Enter your choice: 2

Current Directory: /path/to/your/current/directory
[D] Subdirectory1
[F] File1.txt
[F] File2.txt

Options:
1. Enter a directory
2. Go up one level
3. Exit
Enter your choice: 3