본문 바로가기

프로그래밍 언어/C++

파일 입력 스트림

파일 입력 std::ifstream

  • #include <fstream>으로 포함한다.
  • ifstream 클래스의 객체는 filebuf 객체를 internal stream buffer로 유지하며 연결된 파일에대해 입출력 작업을 수행한다. = 버퍼를 가져와서 입출력 작업을 할 수 있다.

간단 예제

hello.txt 내용

hello world
hello world
hello world

 

#include <iostream>
#include <fstream>

int main()
{
	std::ifstream fin;	// 스트림 열기
	fin.open("hello.txt");	// 파일 open
	char c;

	if(fin.is_open()) // 파일 open 여부 확인
    {
        while(fin.get(c))	// 한 문자씩 가져오기
            std::cout << c;
        fin.close();	// 스트림 닫기
    }

    return 0;
}

 

hello world
hello world
hello world

Process returned 0 (0x0)   execution time : 0.014 s
Press any key to continue.

 

멤버함수

open

void open (const char* filename,  ios_base::openmode mode = ios_base::in);

open("파일명", 오픈 모드);

 

오픈 모드에는 ios_base::in (입력), ios_base::out (출력), ios_base::binary (바이너리)등이 있다.

default 값은 ios_base::in이다

 

is_open

bool is_open();

스트림이 현재 파일에 연결되어 있는지 여부를 반환한다.

 

close

void close();

객체와 연결된 파일을 닫고 스트림과 파일을 연결해제한다.

close를 안해도 객체의 소멸자가 호출되면 자동 close된다. 하지만 규모가 큰 프로젝트에서는 소멸자가 늦게 호출되는 경우도 종종 발생하므로 잊지말고 close 해줘야한다. close하는 습관을 들이자

 

get

int get();
istream& get(char& c);	// c에 char 문자 하나를 저장한다.
istream& get(char* s, streamsize n);	// s 문자열에 n만큼의 문자수를 저장한다.
istream& get(char* s, streamsize n, char delim);  // delim이나오기전까지 최대 n개의 문자열 저장
istream& get(streambuf& sb);	// 출력 스트림 버퍼에 저장
istream& get(streambuf& sb, char delim);

 

 

위치를 기억해서 get을 여러번 호출하면 입력 지정 위치를 저장해서 다음 위치의 value를 반환한다. (아래 예시 참조)

// istream::get example
#include <iostream>     // std::cin, std::cout
#include <fstream>      // std::ifstream

int main () {
    std::ifstream is("hello.txt");     // open file

    char a[5];
    is.get(a, 5);
    std::cout << a << std::endl;

    char c;
    while (is.get(c))          // loop getting single characters
        std::cout << c;

    is.close();                // close file

    return 0;
}

 

컴파일 후 실행

hell
o world
hello world
hello world

Process returned 0 (0x0)   execution time : 0.036 s
Press any key to continue.

 

getline

istream& getline(char* s, streamsize n);
istream& getline(char* s, streamsize n, char delim);

 

getline도 마찬가지로 읽을 때마다 입력 지정 위치를 저장한다.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ifstream fin("hello.txt");
	char line[100];
	fin.getline(line, sizeof(line));	// 한 줄 읽기
    
	while(fin.getline(line, sizeof(line)))	// 한 줄씩 읽어서 출력
		cout << line << endl;
	fin.close();
	return 0;
}

 

hello world
hello world

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.

 

eof

bool eof() const;

파일 끝에 도달하였을때 true를 리턴한다

 

seekg

basic_istream& seekg(pos_type pos);                              // (1)
basic_istream& seekg(off_type off, std::ios_base::seekdir dir);  // (2)

pos: 절대위치

off: 상대위치

dir: 상대위치 기준점

 

std::ios::beg 처음위치

std::ios::end 마지막위치

std::ios::cur 현재위치 

 

get이나 getline으로 파일을 읽다가 처음부터 다시 읽고 싶을때

fin.seekg(0);
fin.seekg(0, std::ios::beg);

위 코드를 통해서 옮길수 있다.

 

출처:

https://www.cplusplus.com/reference/fstream/ifstream/

 

ifstream - C++ Reference

 

www.cplusplus.com

 

'프로그래밍 언어 > C++' 카테고리의 다른 글

파일 입출력 Binary  (0) 2022.03.15
파일 출력 스트림  (0) 2022.03.11
파일 입출력  (0) 2022.03.10
String 클래스  (0) 2022.03.09
클래스와 구조체에 관한 고찰 in C++  (0) 2022.03.04