파일 모드는 ios클래스에 정의된 상수를 사용한다.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
cout << "test.txt에 저장됩니다 (종료 :ctrl+z)" << endl;
ofstream fout;
fout.open("test.txt"); // open으로 파일을 연다
char ch;
while (cin.get(ch)) {
fout << ch;
}
fout.close(); // 파일 스트림을 다 쓰면 닫아야 한다.
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("test1.txt"); // 생성자로 파일을 연다
if (!fin.is_open()) {
cout << "파일 열기에 실패 하였습니다." << endl;
exit(1);
}
char ch;
while (fin.get(ch)) {
cout << ch;
}
fin.close();
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
class Point {
int x;
int y;
public :
Point(int x=0, int y=0): x(x), y(y) {}
void showInfo() {
cout << "[" << x << "," << y << "]" << endl;
}
};
int main() {
Point pos1(10, 30);
Point pos2(40, 80);
ofstream fout("point.bin", ios::binary);
// pos1의 주소를 char*로 형변환 후 Point의 바이트 크기만큼 쓴다
fout.write((char*)&pos1, sizeof(Point));
fout.write((char*)&pos2, sizeof(Point));
fout.close();
Point pos3, pos4;
ifstream fin("point.bin", ios::binary);
fin.read((char*)&pos3, sizeof(Point));
fin.read((char*)&pos4, sizeof(Point));
fin.close();
pos3.showInfo();
pos4.showInfo();
return 0;
}