Language/C++

[TheSSEN/C++] 12. 파일 입출력

coco_daddy 2025. 1. 31. 16:47
※ LIG Nex1 The SSEN Embedded SW School에서 진행된 내용을 정리한 포스팅입니다.

파일 입출력

 

https://cplusplus.com/reference/ios/

header Input-Output base classes Header providing base classes and types for the IOStream hierarchy of classes: Types Class templates basic_iosBase class for streams (type-dependent components) (class template)fposStream position class template (class temp

cplusplus.com

iostream

C에서부터 제공된 입출력 함수들을 C++는 객체화하여 제공하고 있다.

istream

  • get(), getline(), read() 제공
  • buffer
    • 입출력 속도를 높이기 위해 메모리에 임시로 저장하는 공간
    • 버퍼를 기준으로 하는 full buffer와 개행(new line)을 기준으로 하는 line buffer방식이 있다.
  • get()
    • delimiter를 스트림에 남긴다.
  • getline()
    • delimiter를 읽고 무시한다.
  • read()
    • 읽을 길이를 지정하여, 해당 길이만큼 버퍼에서 읽어온다.

cin

  • console input
    • 입력 스트림 중 하나
  • 초기화 하려는 타입과 입력받은 타입이 일치하지 않을 경우 값이 초기화되지 않고 더 이상 입력을 받을 수 없다.
    • cin의 상태를 초기화 해야 한다.
    • string으로 받은 뒤 변환을 하는 것이 안전하다.
  • 입력의 에러 핸들링
    • 스트림의 상태비트를 통해 스트림의 상태를 알 수 있다.
    • cin.fail(), cin.good(), cin.eof(), cin.bad()
  • 스트림 자체로 스트림의 유효성을 확인할 수 있다.
while (cin) {
	cin >> input;
	if (cin)
		cout << "input stream is ok\n";
	else
		cout << "input stream is bad\n";
}
  • put(), write() 제공

File IO stream

  • ifstream, ofstream
  • open mode의 종류
    • ios_base::out
      • 쓰기 가능
    • ios_base::in
      • 읽기 가능
    • ios_base::app
      • append: 파일 뒤 부터 내용 추가 가능
    • ios_base::ate
      • end of file 부터 open
    • ios_base::trunc
      • truncate 모드, 파일의 내용이 처음부터 덮어씌워진다.
    • ios_base::binary
      • 바이너리 모드
  • file output 예제
string fileName = "myFile.dat"
ofstream output(fileName, ios_base::out | ios_base::app);
if (!output) {
	cerr << "Error: file open error: " << fileName << endl;
	exit(1);
}
output << "output content" << endl;
output.close();
  • file input 예제
ifstream fin;
fin.open(fileName);
if (fin.is_open()) {
	cout << "file의 내용은 다음과 같습니다.\n";
	while (fin.get(ch))
		cout << ch;
	fin.close();
}

※ 질문, 개선점, 오류가 있다면 댓글로 남겨주세요 :)