본문 바로가기

프로그래밍 언어/C++

파일 출력 스트림

std::ofstream

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

예시)

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

int main () {
    std::ofstream fout;	// stream
    fout.open("GoodBye.txt");	// open stream

    if (fout.is_open())	// open 확인
    {
        fout << "Good Bye" << std::endl;	// 입력
        fout.close();	// stream 닫기
    }

    return 0;
}

 

멤버함수

 

open

void open (const char* filename,  ios_base::openmode mode = ios_base::out);
  • open("파일명", ios_base::out)    // 디폴트 값이 ios_base::out 이다.
  • 파일이 존재하지 않으면 파일을 만들고 파일이 존재한다면 전부 지우고 새로 만든다. (디폴트)
  • ios_base::app을 두번째 인자로 주면 파일을 지우지 않고 뒤에 덧붙인다.

 

is_open

bool is_open();
  • 파일이 열려있으면  true를 반환한다.

 

close

void close();
  • 파일을 닫는다.

 

put

ostream& put (char c);
  • char 문자 하나를 입력한다.

 

write

ostream& write (const char* s, streamsize n);
  • write("문자열", n)    // 길이 n만큼 문자열을 입력한다.

 

<<

ostream& operator<< (streambuf* sb );
  • 문자열을 입력한다.    // endl을 붙이면 개행까지 입력된다.

 

 

 

출처: 

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

 

ofstream - C++ Reference

 

www.cplusplus.com

 

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

펑터(Functor)를 쓰는 이유  (0) 2022.03.18
파일 입출력 Binary  (0) 2022.03.15
파일 입력 스트림  (0) 2022.03.10
파일 입출력  (0) 2022.03.10
String 클래스  (0) 2022.03.09