Transcript
Page 1: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

C++ 그래 문

12 파 출

파 출 초

파 열 , 사 , 닫

파 출 드

문 단 파 출

스트 파 과 파

read, write 수에 파 출

접근

출 스트림 상태

출 연산 과 파 출

Page 2: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 1

1. 파 출 초

파 출

n 출 객체 cin, cout에 당 는 파 출 스트림 객체만 만

들 수 다 본적 사 출 과 동

파 출 스트림 객체 생

n <fstream> 헤 파

n 객체 : ifstream fin(“in.dat”);

n 출 객체 : ofstream fout(“out.dat”);

n 출 객체 : fstream fio(“data.dat”);

Page 3: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 2

2. 파 열 , 사 , 닫

파 출 과정

1. 출 스트림 ofstream 객체 생

Ø ofstream fout;

2. 생 ofstream 객체 를 출 파 연결

Ø fout.open(“out.dat”);

ü void open(const char *fName, int nMode);

ü fout.open("C:\data\out.dat", ios_base::out | ios_base::trunc);

• nMode에 는 다 절에

Ø또는 1, 2를 동시에 수 : ofstream fout(“out.dat”);

3. 출 객체(cout) 동 사

Ø fout << “test” << endl;

4. 파 연결 제

Ø fout.close();

ü fout 객체 체가 는 것 님

à fout.open() 또 다른 파 연결 가능

Page 4: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 3

2. 파 열 , 사 , 닫

출 : 1 20 정수 3 수를 “out.txt” 출

#include <iostream>#include <fstream>using namespace std;

int main(void){

ofstream fout("out.txt"); // 출 스트림 생 및 파 열기

if (!fout) { // 에러 처리cout << "파 열기 에러" << endl;return 1;

}

for (int i = 1; i <= 20; i++) {if (i % 3 == 0)

fout << i << " "; // 준 출 과 동 하게 사}

fout.close();

return 0;}

파 열 에러 생

à failbit 1 경 (11.9절)

ofstream 클래스는 ! 연산

fail 경 true를

if (fout == NULL) { … } 같 사 가능

fout 수(15.2절)를 fail

경 NULL 수

Page 5: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 4

2. 파 열 , 사 , 닫

: 파 끝(EOF) 만날 값 계를 출

int main(void){

int Num;int Sum = 0;ifstream fin("out.txt"); // 스트림 생 및 파 열기

if (fin == NULL) {cout << "파 열기 에러" << endl;return 1;

}

fin >> Num;

while (!fin.eof()) {Sum += Num;fin >> Num;

}

cout << "합계 : " << Sum << endl;

fin.close();

return 0;}

cin 사 과 동

Page 6: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 5

3. 파 출 드

void open(const char *fName, int nMode);

n 파 출 드

Ø 파 열 드 : , 쓰 등

Ø 접근 드 : 스트 드, 드

n 파 출 클래스들 폴트 출 드

상수 미

ios_base::in 파 열

ios_base::out 출 파 열

ios_base::ate파 열 파 끝 치를 찾 끝 치 동파 출 파 든 치에 가능

ios_base::app파 에 출 파 끝에 추가파 출 파 마 막 치에만 가능 만

든 치에 가능

ios_base::trunc 동 름 파 존 파 든 내 삭제

ios_base::binary 식 파 열

클래스 폴트 파 열 드

ifstream ios_base::in

ofstream ios_base::out | ios_base::trunc

fstream ios_base::in | ios_base::out

Page 7: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 6

3. 파 출 드

C C++

파 출 드 비

스트 드

드 차

n 꿈 문

Ø 캐리 리 (\n)

Ø 라 드(\r)

C++ 드C 드

binary in out trunc app

● “w”

● ● “a”

● ● “w”

● “r”

● ● “r+”

● ● ● “w+”

● ● “wb”

● ● ● “ab”

● ● ● “wb”

● ● “rb”

● ● ● “r+b”

● ● ● ● “w+b”

스트 드

out만 정 동

trunc 처리가

Page 8: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 7

3. 파 출 드

: 스트 드 드 차

int main(void)

{

ofstream fout("out3.txt", ios_base::out | ios_base::trunc | ios_base::binary);

fout << 'a' << endl << 'b' << endl << 'c' << endl;

fout.close();

return 0;

}

스트 드

ios_base::binary를 삭제 경

ios_base::binary를 추가 경

적 처리

- 스트 드 저 à 스트 드

- 드 저 à 드

Page 9: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 8

4. 문 단 파 출

문 단 출 수들

n 본적 사 11.7절, 11.8절과 동

타 문 수

n int peek(void); // 단 다 문 가 무 (제거 X)

n istream &putback(char c); // 마 막 문 (c)를 돌림

int get(void); 문 1개

istream &get(char &) 문 1개 , 연 출 가능

ostream &put(char) 문 1개 , 연 출 가능

istream &get(char *, int, char = ‘\n’)정 개수 또는 단 문 열 ,

‘\n’ 제거

istream &getline(char *, int, char = ‘\n’);정 개수 또는 단 문 열 ,

‘\n’ 제거

Page 10: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 9

int main(void){

ifstream fin("in4.txt");ofstream fout("out4.txt");

if (!fin || !fout) {cout << "파 열기 에러" << endl;return 1;

}

char ch = fin.get(); // 문 하나

while (!fin.eof()) {fout.put(ch); // 문 하나 출fin.get(ch);

}

fin.close();fout.close();

return 0;}

4. 문 단 파 출

: get, put 수를 파 복사

Page 11: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 10

5. 스트 파 과 파

상적 컴퓨 사 에 스트 파 과 파

n 스트 파 : 에 파

n 파 : MS 워드 파 , 래 파 등

그래 점에 스트 파 과 파

n 스트 파 : 저 시 든 를 문 여 저 는 것

Ø : int a = 15; à ‘1’과 ‘5’라는 문 저 à 2 트

n 파 : 저 시 리 태 그 저 는 것

Ø : int a = 15; à 리 태 그 저 à 4 트

다 파 스트 파 가 파 가?

n 파 만든 그래 만 답 가능

Ø 스트 파 : ‘A’, ‘A’, ‘A’, ‘A’ 4개 문 출

Ø 파 : int a = 1094795585; 를 4 트 태

그 출

ü 0X41414141 à AAAA 출

Page 12: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 11

5. 스트 파 과 파

스트 파 과 파 만드는

n 파 스트림 클래스 수에 라 달라짐

n 스트 파 저 : << 연산

n 스트 파 : >> 연산

n 파 저 : write

n 파 : read

주 사

n 파 열 드( 스트 드, 드) 스트 파

파 원칙적 무

n 그러나, 적 스트 파 스트 드 열고, 파

드 열

Page 13: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 12

6. read, write 수에 파 출

read, write 수 타

n istream &read(unsigned char *buffer, int size);

n ostream &write(const unsigned char *buffer, int size);

Ø buffer : 출 또는 를 저 수 주

Ø size : 크 ( 트 단 )

int main(void){

ofstream fout("ex5.dat", ios_base::out | ios_base::binary); // 출 스트림double nums[4] = { 1.1, 2.2, 3.3, 4.4 };fout.write((char *) nums, sizeof(nums)); // double(8)*4개=32바 트 출fout.close();

ifstream fin("ex5.dat", ios_base::in | ios_base::binary);fin.read((char *) nums, sizeof(nums));for (int i = 0; i < 4; i++)

cout << nums[i] << '\t';cout << endl;

cout << "총 바 트 수 : " << fin.gcount() << endl;

return 0;}

Page 14: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 13

6. read, write 수에 파 출

조체 수 파 출

struct Point {int x, y;

};

int main(void){

Point Po;

ofstream fout("ex6.dat",ios_base::out | ios_base::app | ios_base::binary);

cout << "좌 x, y : ";cin >> Po.x >> Po.y;

while (Po.x != 0 && Po.y != 0) {fout.write((char *) &Po, sizeof(Point)); // Point 크기(8)만큼 출cout << "좌 x, y : ";cin >> Po.x >> Po.y;

}

fout.close();

Page 15: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 14

6. read, write 수에 파 출

조체 수 파 출 (계 )

cout << "<< 저 Point 데 터 >>" << endl;

ifstream fin("ex6.dat", ios_base::in | ios_base::binary);

while (fin.read((char *) &Po, sizeof(Point))) {cout << "(" << Po.x << ", " << Po.y << ")" << endl;

}

fin.close();

return 0;}

Page 16: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 15

7. 접근

스트림 포

n 포 (get pointer) : 다 수 는 치를 가리킴

n 출 포 (put pointer) : 다 출 수 치를 가리킴

n 과 출 동 출 트 수만큼 다 치

포 출 포 를 치 동 는

n seekg, seekp 수 사

istream &seekg(streampos pos);

ostream &seekp(streampos pos);

istream &seekg(streamoff off, ios_base::seek_dir dir);

ostream &seekp(streamoff off, ios_base::seek_dir dir);

streampos, streamoff는

long 타 과 동값 미

ios_base::beg 파 처 치를 새 치 동

ios_base::cur 파 치를 새 치 동

ios_base::end 파 마 막 치를 새 치 동

Page 17: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 16

7. 접근

포 출 포 치를 는

n streampos tellg();

n streampos tellp();

seekg tellg 수 적

접근 파 에 보다 적

n int 값들 저 는 경 50 째 int 값 동

n fin.seekg((50 - 1) * 4); // 파 경 가능

Page 18: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 17

struct Point {int x, y;

};

int main(void){

Point Po = { 1, 1 };

fstream fio("ex7.dat", ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);

for (int i = 0; i < 5; i++)fio.write((char *) &Po, sizeof(Point));

fio.seekp(2 * sizeof(Point), ios_base::beg); // 출 포 터를 3번째 원Po.x = 2; Po.y = 2;fio.write((char *) &Po, sizeof(Point));

fio.seekg(0, ios_base::beg); // 포 터를 첫 번째 원 동while (fio.read((char *) &Po, sizeof(Point))) {

cout << "(" << Po.x << ", " << Po.y << ")" << endl;}fio.close();

return 0;}

7. 접근

: (1, 1) 좌 를 5개 저 째 좌 를 (2, 2) 경

Page 19: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 18

8. 출 스트림 상태

파 출 스트림 상태

n 출 스트림 상태 처리 과 동 : 11.9절

int main(void) {int a;

ifstream fin("ex8.dat");fin >> a;

if (fin.fail())cout << "fail" << endl;

elsecout << "not fail" << endl;

fin.clear();

if (fin.fail())cout << "fail" << endl;

elsecout << "not fail" << endl;

fin.close();

return 0;}

는타 를

는 경 à fail

Page 20: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 19

9. 출 연산 과 파 출

CPoint 클래스에 출 연산 : 7.9절

n CPoint Po;

n cin >> Po;

n cout << Po;

다 과 같 식 파 출 원 다 ?

n fin >> Po;

n fout << Po;

원리

à istream, ostream 클래스에

출 연산 만 충

ostream &operator<<(ostream &os, CPoint &Po)

{

os << "(" << Po.x << ", " << Po.y << ")" << endl;

return os;

} ostream 클래스는 ofstream 클래스 base 클래스 므

fout << Po;에 fout 객체를 수 .

결 ofstream 객체 fout 출 .

Page 21: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 20

9. 출 연산 과 파 출

CPoint 클래스에 출 연산

class CPoint {private :

int x, y;

public :CPoint(int a = 0, int b = 0) : x(a), y(b) { }friend istream &operator>>(istream &is, CPoint &Po);friend ostream &operator<<(ostream &os, CPoint &Po);

};

istream &operator>>(istream &is, CPoint &Po) // >> 연산 버 딩{

is >> Po.x >> Po.y;return is;

}

ostream &operator<<(ostream &os, CPoint &Po) // << 연산 버 딩{

os << Po.x << " " << Po.y << endl;return os;

}

Page 22: 12장파일입출력 - contents.kocw.or.krcontents.kocw.or.kr/document/CPP12_File IO.pdf · 12장파일입출력 2 2. 파일열기, 사용하기, 닫기 파일출력과정 1. 출력스트림을위한ofstream

12 파 출 21

9. 출 연산 과 파 출

CPoint 클래스에 출 연산 (계 )

int main(void) {int i;CPoint Po[5];

for (i = 0; i < 5; i++) {cout << "좌 (x, y) : ";cin >> Po[i];

}

ofstream fout("ex9.dat");for (i = 0; i < 5; i++)

fout << Po[i]; // << : ofstream 객체에도 적 가능fout.close();

ifstream fin("ex9.dat");CPoint Temp;for (i = 0; i < 5; i++) {

fin >> Temp;cout << Temp;;

}fin.close();

return 0;}


Recommended