닌자고양이
[C++] ifstream 으로 텍스트 파일 읽는 방법들 본문
ifstream, ofstream 은 생성자에 ios::binary 옵션을 주지 않으면 기본적으로 텍스트 모드로써,
- 개행 문자(윈도우 CR+LF, 유닉스 LF, 맥 CR)를 읽을 때는 LF 로 치환해 읽어오고, 쓸때는 LF 를 해당 OS별 개행 문자로 치환해 저장한다.
- 스트림 종료 문자(윈도우 CTRL+Z(0x1A), 맥/유닉스 CTRL+D(0x04))가 발견시 스트림 또는 파일의 끝으로 간주해 더 이상 읽기는 실패하며 eof() 는 true 가 된다.
1.한 문자씩 읽기
#include <fstream> #include <iostream> using namespace std; int main() { ifstream file("file.txt"); while (!file.eof()) cout << file.get(); }
2.한 줄씩 읽기
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { string str; ifstream file("file.txt"); while (getline(file, str)) cout << str << '\n'; }
3. 버퍼 블록 단위 읽기
#include <fstream> #include <iostream> using namespace std; int main() { char buf[5]; ifstream file("file.txt"); while (file) // operator bool() = IO 오류 없으면 true { file.read(buf, 4); buf[file.gcount()] = '\0'; // gcount() = 읽은 문자 수 cout << buf; } }
4.한번에 파일 전체 읽기 (stringstream 사용)
#include <fstream> #include <sstream> using namespace std; int main() { ifstream file("file.txt"); stringstream ss; ss << file.rdbuf(); cout << ss.str(); }
5.한번에 파일 전체 읽기 (istreambuf_iterator 사용)
#include <fstream> #include <string> using namespace std; int main() { ifstream file("file.txt"); istreambuf_iterator<char> begin(file), end; cout << string(begin, end); }
'C C++' 카테고리의 다른 글
[C/C++] 반복문 없이 정수의 10진수 자릿수 구하기 (0) | 2020.10.04 |
---|---|
[C/C++] 문자열 분리 (strpbrk, strtok, find_first_of 사용) (0) | 2020.10.03 |
[C/C++] UTF-8 텍스트 파일 읽는 방법들 (0) | 2020.09.18 |
[C/C++] 중간값 구하기 mid(a, b, c) (0) | 2020.09.09 |
[C/C++] 공백으로 구분된 정수 배열 입력 받기 (split) (0) | 2020.01.20 |