[ c++ ] 파일 입출력 (ifstream, ofstream)

채명석·2021년 12월 27일
0

cpp

목록 보기
6/11

스트림의 파일연결방법

open하기

# include <fstream>

void open (const char* fileName, ios_base::openmode mode = ios_base::in);
void open (const string& fileName, ios_base::openmode mode = ios_base::in);
  • 첫 번째 인자
    파일 명

  • 두 번째 인자

    • ios_base::in (ifstream의 기본값)
      read를 하기위해
    • ios_base::out (ofstream의 기본값)
      write를 하기위해
    • ios_base::binary
      파일을 바이너리 형태로 open
  • 파일과 연결하기

ifstream	in;
ofstream	out;
in.open(filename); //선언 후 open
out.open(filename);

ifstream	in(filename); //선언과 동시에 open
ofstream	out(filename);

에러체크

함수 is_open과 fail로 체크가 가능합니다.

ifstream	in(filename);

 //ofstream도 동일
if (!in.is_open())
...
//혹은
if (in.fail())
...

파일 닫기

c언어에서는 항상 파일을 open했다면 꼭 닫아줘야 했지만 cpp에서는 소멸자를 통해서 자원을 회수하니 꼭 할 필요는 없지만 명시적으로 닫아주는 게 좋다고 합니다.

ifstream	in(filename);
...
in.close(); //ofstream도 동일

입력(ifstream)

ifstream은 풀어쓰면 input file stream으로 cpp에서 사용하는 파일 입력에 접근할 수 있는 방법 중 하나입니다.

ifstream 사용가능 함수 정리

get

파일에서 한 글자씩 받아온다.

함수원형
istream& get (char& c);

사용
std::ifstream is(str);

char c;
is.get(c);

getline

한 줄 씩 받아온다.

  • 함수원형

  • istream& getline (char* s, streamsize n );
    s에 n만큼 받아옵니다. 중간에 구분자나 eof가 오면 읽기를 중단합니다.
    istream& getline (char* s, streamsize n, char delim );
    s에 n만큼 받아옵니다. 중간에 delim이나 구분자, eof가 오면 읽기를 중단합니다.

  • 사용예시

int main () {
  char name[256], title[256];

  std::cout << "Please, enter your name: ";
  std::cin.getline (name,256);

  std::cout << "Please, enter your favourite movie: ";
  std::cin.getline (title,256);

  std::cout << name << "'s favourite movie is " << title;

  return 0;
}

seekg

현재 스트림의 위치지정자를 설정합니다.

  • 함수원형

  • istream& seekg (streampos pos);
    스트림의 시작지점을 기준으로 pos만큼 움직입니다.

  • istream& seekg (streamoff off, ios_base::seekdir way);
    way를 기준으로 off만큼 움직입니다. 기준은 다음과 같습니다.

ios_base::beg스트림의 시작지점
ios_base::cur위치지정자의 현재 위치
ios_base::end스트림의 끝
  • 사용 예시
int main () {
  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    is.seekg (0, is.end); //위치지정자를 스트림의 끝으로 이동
    int length = is.tellg(); // 현재 위치를 저장
    is.seekg (0, is.beg); //위치지정자를 스트림의 시작으로 이동

    // allocate memory:
    char * buffer = new char [length];

    // read data as a block:
    is.read (buffer,length); // 스트림 is에서 데이터를 length만큼 buffer에 저장

    is.close();

    // print content:
    std::cout.write (buffer,length);

    delete[] buffer;
  }

  return 0;
}

tellg

현재 위치지정자의 위치를 반환합니다.

  • 함수원형
    streampos tellg();

  • 사용 예시 (seekg와 동일합니다.)

int main () {
  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    is.seekg (0, is.end); //위치지정자를 스트림의 끝으로 이동
    int length = is.tellg(); // 현재 위치를 저장
    is.seekg (0, is.beg); //위치지정자를 스트림의 시작으로 이동

    // allocate memory:
    char * buffer = new char [length];

    // read data as a block:
    is.read (buffer,length); // 스트림 is에서 데이터를 length만큼 buffer에 저장

    is.close();

    // print content:
    std::cout.write (buffer,length);

    delete[] buffer;
  }

  return 0;
}

read

스트림으로부터 데이터를 읽어들입니다.

  • 함수원형
    istream& read(char* s, streamsize n);
    s에 n만큼 데이터를 읽어들입니다.

  • 사용예시 (seekg와 동일합니다.)

int main () {
  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    is.seekg (0, is.end); //위치지정자를 스트림의 끝으로 이동
    int length = is.tellg(); // 현재 위치를 저장
    is.seekg (0, is.beg); //위치지정자를 스트림의 시작으로 이동

    // allocate memory:
    char * buffer = new char [length];

    // read data as a block:
    is.read (buffer,length); // 스트림 is에서 데이터를 length만큼 buffer에 저장

    is.close();

    // print content:
    std::cout.write (buffer,length);

    delete[] buffer;
  }

  return 0;
}
std::string str
is.read( &str[0], size );

위 내용처럼 사용해서 string을 사용할 수 있습니다.

출력(ofstream)

output file stream으로써 출력을 담당합니다.

ofstream 사용가능 함수 정리

write

  • 함수원형
    ostream& write (const char* s, streamsize n);
    스트림으로 s를 n만큼 출력합니다.

operator<<

cout처럼 사용이 가능합니다.

std::ofstream	out(filename);

out << _filestr;

[ c++ ] namespace
[ c++ ] 클래스, 생성자, 소멸자, 이니셜라이저, this포인터
[ c++ ] c++에서의 const와 static
[ c++ ] 참조자(reference)
[ c++ ] new와 delete
[ c++ ] 함수 오버로딩
[ c++ ] 파일 입출력 (ifstream, ofstream)
[ c++ ] 함수포인터, 멤버 함수포인터
[ c++ ]연산자 오버로딩
[ c++ ] 캡슐화란?
[ c++ ] 상속과 다형성에 대해 알아보자

0개의 댓글