fstream 을 사용하여 바이너리 파일 작업
이 단계에서는 C++ 에서 fstream 클래스를 사용하여 바이너리 파일 작업을 수행하는 방법을 배웁니다. 바이너리 파일은 텍스트 파일과 달리 데이터를 원시 바이너리 형식으로 저장하며, 구조화된 데이터를 효율적으로 저장하는 데 유용합니다.
binary_files.cpp라는 새 C++ 파일을 생성합니다:
touch ~/project/binary_files.cpp
binary_files.cpp 파일에 다음 코드를 추가합니다:
#include <iostream>
#include <fstream>
#include <string>
// 바이너리 파일 쓰기를 시연하기 위한 간단한 구조체
struct Student {
int id;
char name[50];
double gpa;
};
void writeBinaryFile() {
std::fstream binaryFile("students.bin", std::ios::out | std::ios::binary);
if (!binaryFile) {
std::cerr << "Error opening file for writing!" << std::endl;
return;
}
// 학생 레코드 생성
Student students[3] = {
{1, "John Doe", 3.5},
{2, "Alice Smith", 3.8},
{3, "Bob Johnson", 3.2}
};
// 전체 구조체를 바이너리 파일에 쓰기
binaryFile.write(reinterpret_cast<char*>(students), sizeof(students));
binaryFile.close();
std::cout << "Binary file written successfully!" << std::endl;
}
void readBinaryFile() {
std::fstream binaryFile("students.bin", std::ios::in | std::ios::binary);
if (!binaryFile) {
std::cerr << "Error opening file for reading!" << std::endl;
return;
}
Student students[3];
// 전체 구조체를 바이너리 파일에서 읽기
binaryFile.read(reinterpret_cast<char*>(students), sizeof(students));
std::cout << "Student Records:" << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << "ID: " << students[i].id
<< ", Name: " << students[i].name
<< ", GPA: " << students[i].gpa << std::endl;
}
binaryFile.close();
}
int main() {
// 바이너리 파일 쓰기
writeBinaryFile();
// 바이너리 파일 읽기
readBinaryFile();
return 0;
}
프로그램을 컴파일합니다:
g++ binary_files.cpp -o binary_files
실행 파일을 실행합니다:
./binary_files
예상 출력:
Binary file written successfully!
Student Records:
ID: 1, Name: John Doe, GPA: 3.5
ID: 2, Name: Alice Smith, GPA: 3.8
ID: 3, Name: Bob Johnson, GPA: 3.2
바이너리 파일에 대한 주요 사항:
- 바이너리 모드에는
std::ios::binary 플래그를 사용합니다.
- 바이너리 데이터 처리를 위한
write() 및 read() 메서드.
- 유형 간 변환을 위해
reinterpret_cast가 사용됩니다.
- 구조화된 데이터를 효율적으로 저장하는 데 유용합니다.
- 데이터의 정확한 바이너리 표현을 보존합니다.
바이너리 파일을 정밀한 청사진이라고 생각할 수 있습니다. 텍스트 변환 없이 메모리에 존재하는 그대로 데이터를 저장합니다.