[c++] 이진 파일 입출력

C++을 사용하여 이진 파일을 읽고 쓰는 것은 데이터를 효율적으로 저장하고 전송하는 데 유용합니다. 다음은 C++에서 이진 파일을 읽고 쓰는 방법에 대한 간단한 예제입니다.

이진 파일 쓰기

#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("data.bin", std::ios::binary);

    if (file.is_open()) {
        int data[] = {1, 2, 3, 4, 5};

        file.write((char*)data, sizeof(data));

        file.close();
    } else {
        std::cout << "Failed to open the file for writing" << std::endl;
    }

    return 0;
}

위의 코드는 data.bin이라는 이진 파일을 생성하고 정수 배열을 이진 형식으로 파일에 씁니다.

이진 파일 읽기

#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("data.bin", std::ios::binary);

    if (file.is_open()) {
        int data[5];

        file.read((char*)data, sizeof(data));

        for (int i = 0; i < 5; i++) {
            std::cout << data[i] << " ";
        }

        file.close();
    } else {
        std::cout << "Failed to open the file for reading" << std::endl;
    }

    return 0;
}

위의 코드는 data.bin이라는 이진 파일에서 데이터를 읽고 콘솔에 출력합니다.

요약

이진 파일을 C++로 읽고 쓰는 것은 간단하지만 주의해야 할 점이 있습니다. 이진 파일을 다룰 때 데이터의 크기와 구조를 정확히 이해하고, 파일 입출력 시에 이를 적절히 처리해야 합니다.

이진 파일 입출력에 대한 자세한 내용은 다음 참고 자료를 참조하시기 바랍니다.

참고 자료

위의 예제 코드와 참고 자료를 통해 C++에서 이진 파일 입출력에 대해 더 자세히 알아보시기 바랍니다.