Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

닌자고양이

[C++] ifstream 으로 텍스트 파일 읽는 방법들 본문

C C++

[C++] ifstream 으로 텍스트 파일 읽는 방법들

닌자고양이 2020. 9. 20. 02:41

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);
}
Comments