📝 스트림 상태 검사
- 스트림 상태
- 파일 입출력이 진행되는 동안 스트림에 관한 입출력 오류 저장
- 스트림 상태를 저장하는 멤버 변수 이용
- eofbit
- failbit
- 정수를 입력받고자 하였으나 문자열이 입력되는 등 포맷 오류나 쓰기 금지된 곳에 쓰기를 시행하는 등 전반적인 IO실패 시 1로 세팅
- badbit
- 스트림이나 데이터가 손상되는 수준의 진단되지 않는 문제가 발생한 경우나 유효하지 않는 입출력 명령이 주어졌을 때 1로 세팅
#include <iostream>
#include <fstream>
using namespace std;
void showStreamState(ios& stream) {
cout << "eof()" << stream.eof() << endl;
cout << "fail()" << stream.fail() << endl;
cout << "bad()" << stream.bad() << endl;
cout << "good()" << stream.good() << endl;
}
int main() {
const char* noExistFile = "c:\\temp\\noexist.txt";
const char* existFile = "c:\\temp\\student.txt";
ifstream fin(noExistFile);
if (!fin) {
cout << noExistFile << "열기 오류" << endl;
showStreamState(fin);
cout << existFile << "파일 열기" << endl;
fin.open(existFile);
showStreamState(fin);
}
int c;
while ((c = fin.get()) != EOF)
{
cout.put((char)c);
}
cout << endl;
showStreamState(fin);
fin.close();
}
📝 임의 접근과 파일 포인터
- C++ 파일 입출력 방식
- 순차 접근
- 읽은 다음 위치에서 읽고, 쓴 다음 위치에 쓰는 방식
- 디폴트 파일 입출력 방식
- 임의 접근
- 파일 내의 임의의 위치로 옮겨 다니면서 읽고 쓸 수 있는 방식
- 파일 포인터를 옮겨 파일 입출력
- 파일 포인터
- 파일은 연속된 바이트의 집합
- 파일 포인터
- 파일에서 다음에 읽거나 쓸 위치를 표시하는 특별한 마크
- C++는 열려진 파일마다 두 개의 파일 포인터 유지
- get pointer : 파일 내에 다음에 읽을 위치
- put pointer : 파일 내에 다음에 쓸 위치
📝 파일크기 계산
#include <iostream>
#include <fstream>
using namespace std;
long getFileSize(ifstream& fin) {
fin.seekg(0, ios::end);
long length = fin.tellg();
return length;
}
int main() {
const char* file = "c:\\windows\\system.ini";
ifstream fin(file);
if (!fin) {
cout << "열기 오류" << endl;
return 0;
}
cout << file << "의 크기는 " << getFileSize(fin);
fin.close();
}