File I/O

headkio·2020년 9월 9일
0

C++

목록 보기
5/35
post-thumbnail

파일 열기

#include <fstream>

ifstream fin;
fin.open("test.txt");

ofstream fout;
fout.open("test.txt");

fstream fs;
fs.open("test.txt");

open()

fin.open("test.txt", ios_base::in | ios_base::binary);

mode flags

  • in
  • out
  • ate
  • app
  • trunc
  • binary

파일 닫기

ifstream fin;

// ...

fin.close();
  • scope를 벗어나면 알아서 해제된다.

Stream 상태 확인

fstream fs;
fs.open("test.txt");

if (fs.is_open())
{
	// ...
}

파일 읽기

파일 읽기 → << (라인 단위)

happy

bad

→ 빈 줄이 출력된다.

파일 읽기 → << (단어 단위 : 숫자만 읽기)

happy

bad

failbit이 설정됐지만 number에는 여전히 300이 들어 있다.

bad

문자를 읽지 못해 fail 했지만 eof는 아니기 때문에 무한 반복

잘못된 입력 처리

while (!fin.eof()) 
{
	fin >> number;

	if (!fin.fail()) 
	{
		cout << number << endl;
		continue;
	}

	if (fin.eof()) 
	{
		break;
	}

	fin.clear();
	fin >> trash;
}

fin.close();

EOF 처리

  • 입출력 연산이 스트림 상태 비트를 변경한다는 사실 기억
  • EOF 잘못 처리하면 무한 루프
  • clear()를 쓸 때는 두 번 생각

테스트

파일 읽기 → read()

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

if (fin.is_open()) 
{
	Record record;
	fin.read((char*)&record, sizeof(Record));
}

fin.close();

파일 쓰기

파일 쓰기 → <<

ofstream fout;
fout.open("test.txt");

string line;
getline(cin, line);
if (!cin.fail()) 
{
	fout << line << endl;
}

fout.close();
  • endl → flush O
  • '\n' → flush X

파일 쓰기 → write()

파일 탐색

// 절대 위치
ios::pos_type pos = fout.tellp() // 쓰기 포인트 위치
ios::pos_type pos = fin.tellg() // 읽기 포인트 위치

fout.seekp(0); // 처음 위치로 이동

// 상대 위치
ios_base::beg // 시작 부터
ios_base::cur // 현재 부터
ios_base::end // 뒤 부터

fout.seekp(20, ios_base::cur); // 현재 위치부터 20 byte 뒤로 이동

>> 과 getline 섞어 쓰지 말자

profile
돌아서서 잊지말고, 잘 적어 놓자

0개의 댓글