c++

11월 11일 fstream 클래스

송시혁 2013. 11. 11. 19:14


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
  fstream fs;      //파일 객체 fs 생성.
  
  fs.open("test.txt", ios::out);  
  //open함수 뒤에 두번째 인자로 ios::out 설정,
  //파일을 출력모드

  if(true==fs.fail())//open함수 실행 여부 검사.
  {
    return 0;
  }
  
  fs << "keyboard" << endl;//파일에 문자열 "keyboard"를 저장.
  fs << "monitor" << endl;// 파일에 문자열 "monitor"를 저장. 
  
  fs.close();    //파일을 닫음.
  
  fs.open("test.txt", ios::app); //ios::app는 파일 추가 모드 
  fs << "desk" << endl;//파일에 문자열 desk를 추가로 저장.
  fs.close();  //파일을 닫음.

  fs.open("test.txt", ios::in);
  //ios::in는 파일에서 내용을 읽기 모드 설정.
  string temp;
  //문자열 변수 temp에 저장.
  
  //파일에 객체를 읽고 파일의 끝이 아니면 반복문 계속 
  while(fs >>  temp, !fs.eof())
  {
    cout << temp << endl;// temp에 담겨져 있는 내용 화면에 출력
  }
  
  fs.close();

  return 0;
}