[c++] C++로 리눅스 파일 시스템 다루기

리눅스 파일 시스템을 다루는 프로그램을 개발할 때 C++를 사용할 수 있습니다. C++는 파일과 디렉토리를 다루기 위한 표준 라이브러리를 제공하고 있으며, 이를 사용하여 파일 입출력 및 디렉토리 조작 기능을 구현할 수 있습니다.

파일 입력 및 출력

C++의 <fstream> 헤더 파일을 사용하여 파일을 읽고 쓸 수 있습니다. 아래는 파일을 읽어오는 예제 코드입니다.

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("example.txt");
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            std::cout << line << std::endl;
        }
        file.close();
    } else {
        std::cout << "Unable to open file";
    }
    return 0;
}

위 코드는 example.txt 파일을 읽어 한 줄씩 터미널에 출력하는 예제입니다.

디렉토리 조작

C++17부터는 <filesystem> 헤더 파일을 통해 파일 시스템을 다룰 수 있는 기능이 추가되었습니다. 디렉토리 생성, 삭제, 파일 및 디렉토리 존재 여부 확인 등의 작업을 할 수 있습니다.

#include <iostream>
#include <filesystem>

int main() {
    std::filesystem::create_directory("new_directory");
    if (std::filesystem::exists("new_directory")) {
        std::cout << "Directory created successfully";
    } else {
        std::cout << "Failed to create directory";
    }
    return 0;
}

위 코드는 new_directory라는 디렉토리를 생성하는 예제입니다.

C++를 사용하여 리눅스 파일 시스템을 다루는 방법에 대한 간단한 소개였습니다. C++ 표준 라이브러리를 활용하여 파일과 디렉토리를 다루는 다양한 기능을 구현할 수 있습니다.