#28 [c++] 스트림 상태 검사, 파일 포인터

정상준·2022년 12월 8일
0

c++

목록 보기
24/25

📝 스트림 상태 검사

  • 스트림 상태
    • 파일 입출력이 진행되는 동안 스트림에 관한 입출력 오류 저장
      • 스트림 상태를 저장하는 멤버 변수 이용
      • eofbit
        • 파일의 끝을 만났을 때 1로 세팅
      • failbit
        • 정수를 입력받고자 하였으나 문자열이 입력되는 등 포맷 오류나 쓰기 금지된 곳에 쓰기를 시행하는 등 전반적인 IO실패 시 1로 세팅
      • badbit
        • 스트림이나 데이터가 손상되는 수준의 진단되지 않는 문제가 발생한 경우나 유효하지 않는 입출력 명령이 주어졌을 때 1로 세팅
#include <iostream>
#include <fstream>


using namespace std;

/*
c:\temp\noexist.txt열기 오류
eof()0
fail()1
bad()0
good()0
c:\temp\student.txt파일 열기
eof()0
fail()0
bad()0
good()1
student
eof()1
fail()1
bad()0
good()0
*/

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;

/*
c:\windows\system.ini의 크기는 219
*/

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();
}
profile
안드로이드개발자

0개의 댓글