파일읽기 ( ifstream )

  • 헤더 : <fstream>
  • input file stream
  • 파일 내용 읽어옴

사용함수

1. open()

- 파일 열 때 사용

 

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

void open( const string& fileName, ios_base::openmode mode = ios_base::in );

첫번째 인자  :  open할 파일명
두번째 인자  :  오픈할 때 모드 설정

         ios::in         :     읽기 위한 파일 열기

         ios::out      :    쓰기 위한 파일 열기

         ios::ate      :    파일의 끝에 위치

         ios::app     :    모든 출력은 파일의 끝에 추가된다.

         ios::trunc   :    만약 파일이 존재하면 지운다.

         ios::binary  :    이진 모드 

 

<두번째 인자 디폴트값>
파일을 열 때 첫번째 인자만 주면 두번째 인자는 클래스별로 디폴트값이 정해진다.

  • ofstream               :                 ios::out | ios::trunc
  • ifstream                :                 ios::in
  • fstream                 :                 ios::in | ios::out

 

사용 예시)

만약 데이터 추가 모드인 이진 모드로 "example.bin"파일을 열길 원한다면?

➡︎  ofstream file;

     file.open("example.bin", ios::out | ios::app | ios::binary);

 

 

2. is_open()

- 열렸는지 확인

 

bool is_open() const;

 

3. close()

- 파일과의 연결을 닫는 함수

 

void close();

 

4. get()

- 읽은 파일에서 문자 단위(char)로 읽어오는 함수

 

ifstream& get(char& c);

 

사용법

char c;
while(readFile.get(c))
{
  cout << c;  // 읽은 문자가 c에 들어있다.
}

 

5. getline()

- 한 줄씩 읽어오는 함수 ( 한 줄씩 문자열을 읽어 str에 저장 )

- 한 줄의 기준은 '\n'이 올 때까지  or 파일의 끝을 알리는 EOF를 만날 때까지

 

ifstream& getline(char* str, streamsize len);

 

<주의사항>

문자열을 받아오는 형태가 char* 타입이기 때문에 string타입으로 바로 받을 수 없다.
str.c_str()로 string을 문자열로 바꿔도 불가능하다.
-> c_str()의 반환값은 const char*이기 때문에 첫번째 매개변수의 타입인 char*와 맞지 않다.

 

6. eof()

- 파일을 읽을 때 커서가 움직이게 되는데 그 커서가 getline(), get()함수를 돌게 되면 쭉쭉 뒤로 가게 된다.

- 파일의 끝이 나오면 true, 아니면 false 반환

 

 bool eof() const;

 

7. read()

- stream에서 문자를 읽어옴

- count개의 문자를 읽어들이거나 EOF가 발생할 때까지 읽어들임

- 읽어들인 문자수는 gcount()를 사용해 알 수 있다

 

basic_istream& read(char_type* s, std::streamsize count);

    - 첫번째 인자  :  읽어들인 문자들을 저장할 문자배열

    - 두번째 인자  :  문자 몇개를 읽을지 설정

 

 

파일읽기 간단 예제

std::ifstream readFile;
readFile.open("test.txt");

if(readFile.is_open())
{
  while(!readFile.eof())
  {
    char arr[256];
    readFile.getline(arr, 256);
  }
}
readFile.close();

 

파일읽기 방법 총정리

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)
  {
    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(); // file과 연관된 스트림버퍼 전체를 리턴한다.
  cout << ss.str();
}

 

 

 

 파일에 쓰기 ( ofstream )

  • 헤더 : <fstream>
  • output file steram

 

사용함수

1. write()

- 파일에 쓰는 함수

- 첫번째 매개변수로 받은 str을 n길이만큼 파일에 write한다.

 

ostream& write(const char* str, streamsize n);

 

 

파일에 쓰기 간단 예제

std::ofstream writeFile;
writeFile.open("test.txt");

char arr[11] = "kkddyy";

if(writeFile.is_open())
{
  writeFile.write(arr, 10);  // char배열로 된 문자열은 끝에 '\0'이 들어가 있기 때문에 
                             // 배열의 "총길이 - 1"만큼만 write해야 한다.
                             // c++ string타입의 문자열로 사용한다면 신경쓰지 않아도 됨!!
}
writeFile.close();

 

+ Recent posts