자료형이나 객체를 바이너리 파일로 입출력할 수 있다.
int 자료형 입출력
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int i = 12;
ofstream fileBinary("MyBinary.bin", ios_base::out | ios_base::binary);
// fileBinary.write((const char *)(&i), sizeof(i));
fileBinary.write(reinterpret_cast<const char *>(&i), sizeof(i));
fileBinary.close();
int getI;
ifstream inputFileBinary("MyBinary.bin", ios_base::in | ios_base::binary);
inputFileBinary.read(reinterpret_cast<char *>(&getI), sizeof(getI));
cout << "getI: " << getI << endl;
inputFileBinary.close();
return 0;
}
객체 입출력
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
class Human
{
private:
char *name;
int age;
public:
Human(){};
Human(const char* inName, int intAge)
:age(intAge)
{
name = new char[strlen(inName)];
strcpy(name, inName);
}
~Human()
{
delete[] name;
}
void ShowInfo()
{
cout << "이름: " << name << endl;
cout << "나이: " << age << endl;
}
};
int main()
{
Human dae("daegil.kim", 25);
dae.ShowInfo();
ofstream fsOut("MyBinary.bin", ios_base::out | ios_base::binary);
if (fsOut.is_open())
{
cout << "Writing one object of Human to a binary file" << endl;
fsOut.write(reinterpret_cast<const char*>(&dae), sizeof(dae));
fsOut.close();
}
ifstream fsIn("MyBinary.bin", ios_base::in | ios_base::binary);
if (fsIn.is_open())
{
Human somePerson;
cout << "Reading one object of Human from a binary file" << endl;
fsIn.read(reinterpret_cast<char*>(&somePerson), sizeof(somePerson));
somePerson.ShowInfo();
fsIn.close();
}
return 0;
}
'프로그래밍 언어 > C++' 카테고리의 다른 글
펑터(Functor)를 쓰는 이유 (0) | 2022.03.18 |
---|---|
파일 출력 스트림 (0) | 2022.03.11 |
파일 입력 스트림 (0) | 2022.03.10 |
파일 입출력 (0) | 2022.03.10 |
String 클래스 (0) | 2022.03.09 |