바이너리 파일 입출력
원시 바이트 읽고 쓰기
바이너리 파일 입출력은(는) CoddyKit의 무료 C++ Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C++ Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C++ Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
텍스트와 바이너리 비교
텍스트 모드는 사람이 읽을 수 있는 문자를 쓰고, 바이너리 모드는 객체가 메모리에 저장된 그대로의 원시 바이트를 씁니다. std::ios::binary로 여십시오.
#include <iostream>
#include <fstream>
int main() {
int value = 12345;
std::ofstream out("v.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&value), sizeof(value));
std::cout << "wrote " << sizeof(value) << " bytes\n";
return 0;
}write가 바이트를 받는 방식
write(ptr, n)은 ptr에서 시작하는 원시 바이트 n개를 출력합니다. 객체의 주소를 const char*로 형 변환해야 합니다.
#include <iostream>
#include <fstream>
int main() {
double d = 3.14;
std::ofstream out("d.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&d), sizeof(d));
out.close();
std::cout << "saved a double\n";
return 0;
}read로 바이트 복원
read(ptr, n)은 ptr이 가리키는 객체에 바이트 n개를 읽어 들여 이진 쓰기를 되돌립니다.
#include <iostream>
#include <fstream>
int main() {
int original = 777;
std::ofstream("i.bin", std::ios::binary).write(reinterpret_cast<const char*>(&original), sizeof(original));
int loaded = 0;
std::ifstream in("i.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(&loaded), sizeof(loaded));
std::cout << loaded << '\n';
return 0;
}POD 구조체 쓰기
단순 데이터 구조체(POD)는 포인터가 없고 멤버 크기가 고정되어 있으므로, 바이트 한 덩어리로 저장하고 다시 불러올 수 있습니다.
#include <iostream>
#include <fstream>
struct Record { int id; double balance; };
int main() {
Record r{1, 99.5};
std::ofstream out("rec.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&r), sizeof(r));
std::cout << "struct saved\n";
return 0;
}구조체 다시 읽기
한 번의 read 호출로 구조체 전체를 복원할 수 있습니다.
#include <iostream>
#include <fstream>
struct Record { int id; double balance; };
int main() {
Record w{42, 250.0};
std::ofstream("r2.bin", std::ios::binary).write(reinterpret_cast<const char*>(&w), sizeof(w));
Record r{};
std::ifstream in("r2.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(&r), sizeof(r));
std::cout << r.id << ' ' << r.balance << '\n';
return 0;
}배열 쓰기
배열의 전체 바이트 크기를 전달하면 한 번의 호출로 배열 전체를 쓸 수 있습니다.
#include <iostream>
#include <fstream>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
std::ofstream out("arr.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(arr), sizeof(arr));
std::cout << "wrote " << sizeof(arr) << " bytes\n";
return 0;
}배열 다시 읽기
같은 크기의 배열에 같은 수의 바이트를 읽어 들이십시오.
#include <iostream>
#include <fstream>
int main() {
int src[5] = {10, 20, 30, 40, 50};
std::ofstream("a2.bin", std::ios::binary).write(reinterpret_cast<const char*>(src), sizeof(src));
int dst[5] = {};
std::ifstream in("a2.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(dst), sizeof(dst));
for (int x : dst) std::cout << x << ' ';
std::cout << '\n';
return 0;
}위치 탐색
seekg(가져오기)와 seekp(넣기)는 읽기 및 쓰기 위치를 이동시켜 파일에서 임의 접근을 가능하게 합니다.
#include <iostream>
#include <fstream>
int main() {
int data[3] = {100, 200, 300};
std::ofstream("seek.bin", std::ios::binary).write(reinterpret_cast<const char*>(data), sizeof(data));
std::ifstream in("seek.bin", std::ios::binary);
in.seekg(sizeof(int)); // skip to second int
int second; in.read(reinterpret_cast<char*>(&second), sizeof(second));
std::cout << second << '\n';
return 0;
}위치 확인
tellg와 tellp는 현재 위치를 알려 주며, 파일 크기나 오프셋을 측정할 때 유용합니다.
#include <iostream>
#include <fstream>
int main() {
int data[4] = {1, 2, 3, 4};
std::ofstream("tell.bin", std::ios::binary).write(reinterpret_cast<const char*>(data), sizeof(data));
std::ifstream in("tell.bin", std::ios::binary);
in.seekg(0, std::ios::end);
std::cout << "file size: " << in.tellg() << " bytes\n";
return 0;
}포인터를 사용하면 안 되는 이유
포인터나 std::string을 포함하는 객체를 이진 형식으로 저장하지 마십시오. 가리키는 데이터가 아니라 포인터 주소를 저장하게 됩니다. 대신 내용을 직렬화하십시오.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string s = "hello";
std::ofstream out("str.bin", std::ios::binary);
std::size_t len = s.size();
out.write(reinterpret_cast<const char*>(&len), sizeof(len));
out.write(s.data(), len); // write the chars, not the object
std::cout << "serialized " << len << " chars\n";
return 0;
}이식성 관련 주의사항
이진 레이아웃은 바이트 순서와 형식의 크기에 따라 달라집니다. 한 플랫폼에서 작성한 파일이 다른 플랫폼에서 올바르게 읽히지 않을 수 있으므로, 공유할 때 사용할 고정 형식을 정의하십시오.
#include <iostream>
#include <cstdint>
int main() {
std::int32_t fixed = 1; // fixed-width type for portability
std::cout << "sizeof int32_t = " << sizeof(fixed) << '\n';
return 0;
}빠른 확인
바이너리 입출력에 대한 이해도를 확인해 보십시오.
복습
이진 파일 입출력을 배웠습니다.
std::ios::binary로 열고,reinterpret_cast<char*>와 함께write/read를 사용합니다seekg/seekp와tellg/tellp로 임의 접근을 수행합니다- 포인터나 문자열을 직접 저장하지 말고 내용을 직렬화해야 하며, 바이트 순서에 주의해야 합니다
다음에는 스트림 상태를 확인하고 오류를 처리하는 방법을 배웁니다.
자주 묻는 질문
“바이너리 파일 입출력” 강의는 무료인가요?
네 — “바이너리 파일 입출력” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C++ Academy 강의 전체를 잠금 해제할 수 있습니다. C++ Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“바이너리 파일 입출력”에서 뭘 배우나요?
원시 바이트 읽고 쓰기 브라우저에서 직접 실행하는 실습 코드로 C++ Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
C++ Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 C++ Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“바이너리 파일 입출력” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 C++ Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 C++ Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- ifstream으로 파일 읽기
- ofstream으로 파일 쓰기
- 바이너리 파일 입출력
- 오류 처리와 상태