[ ofstream & ifstream ]
- 둘을 모두 포함하는 라이브러리인 <fstream>을 include 해서 쓰면 됨 (file stream)
- ostream과 istream을 각각 상속 받은 것이 ofstream, ifstream
- <ostream>, <istream> 각각 헤더로 include해도 되지만, <fstream>이 훨씬 지원하는 기능이 많으므로 파일 입출력 시에는 <fstream>을 include 할 것!
- ofstream
- 파일에 쓸 때 사용
- output file stream : "프로그램의 내용을 파일에 출력한다."
- seekp(), tellp() : put pointer의 현재 위치를 반환 및 변경 (파일에 쓸 때 ofstream과 함께 사용)
- ifstream
- 파일을 읽어올 때 사용
- input file stream : "파일로부터 어떤 내용을 가져와서 프로그램에 입력받는다."
- seekg(), tellg() : get pointer의 현재 위치를 반환 및 변경 (파일을 읽어올 때 ifstream과 함께 쓰임)
[ 파일 삭제(remove) & 파일명 변경(rename) ]
- 파일을 remove하거나 rename하기 전에는 무조건 파일을 close 해줘야 함! (안 닫고 실행 시 처리 안됨)
- remove와 rename 함수의 인자로는 string이 아닌 C-style의 문자열이 들어감
- string.c_str() 로 변환해주기 (string -> const char *)
- ifstream과 ofstream 둘 다 remove와 rename 가능!
- 파일 열고(open) 닫는 것(close)만 잘 하면 ok
#include <fstream>
ifstream in(m_sLogPath); // ofstream으로 해도 상관 X
if (in.is_open()) {
in.seekg(0, ios::end); // 포인터를 파일의 끝으로 옮김 (0 : 파일 끝에서부터의 offset)
size_t size = in.tellg(); // 현재 위치를 읽어 return (파일의 크기)
if (size == 0) {
// 파일 삭제
in.close(); // 열려 있으면 반드시 닫아주고 처리
remove(m_sLogPath.c_str());
}
else {
// 파일명 변경
in.close();
int result = rename(m_sLogPath.c_str(), sFinalLogPath.c_str()); // 삭제 성공 시 0
}
}
[ seekp, tellp, seekg, tellg ]
- seekp, tellp : ofstream과 함께 사용하는 함수
- seekg, tellg : ifstream과 함께 사용하는 함수
- seek : 포인터의 위치를 옮김
- tell : 포인터의 위치를 알려줌
- 이를 이용해 파일의 크기 및 empty 여부를 알 수 있음
in.seekg(0, ios::end); // 파일 끝으로 옮기고(end), 그로부터 offset은 0으로 하므로, 포인터는 맨 끝에 위치
int size = in.tellg(); // 포인터의 위치 return. 0이면 파일은 empty
cf. 참고
https://kasimov.korea.ac.kr/dokuwiki/doku.php/activity/public/2021/cpp/210810
'[ 언어 및 문법 ] > C, C++' 카테고리의 다른 글
[모두의 코드][씹어먹는 C언어] 17. 변수의 생존 조건 및 데이터 세그먼트의 구조 (local, global, static variable) (0) | 2023.11.12 |
---|---|
[모두의 코드][씹어먹는 C++] 1-2. 첫 C++ 프로그램 분석하기 (namespace) (0) | 2023.11.12 |
[C++] enum vs #define (0) | 2022.08.14 |
[C++] bool vs BOOL (0) | 2022.08.14 |
[C++] NAN, isnan() (0) | 2022.08.14 |