※ 스트림(stream)

순서가 있는 데이터의 연속적인 흐름으로 다음과 같은 입출력 관련 클래스가 있다.

  • ofstream  => 출력파일 stream클래스, 출력파일생성 및 파일에 데이터 쓸 때 사용
  • ifstream   => 입력파일 stream클래스, 파일에서 데이터를 읽을 때 사용한다.
  • fstream    => 일반적인 파일 스트림

 

 

※ 파일 읽기

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


int main(){
    ifstream is{"example.txt"};
    string str;

    while(is){
        is >> str;
        cout << str << " ";
    }
    cout << endl;
    // 객체 is가 범위를 벗어나면 ifstream 소멸자가 파일을 닫는다.
}

 

※ 파일 쓰기

 

※ 파일 모드

쉽게 풀어쓴 C 프로그래밍 참조

 

 

 

 

 

※ 파일에서 읽은 data를 객체로 vector에 저장했다 출력하기

class Temperature {
public:
    int hour;
    double temperature;
};

int main(){
    ifstream is{"temp.txt"};
    if (!is){
        cerr << "file open failed" << endl;
        exit(1);
    }

    vector<Temperature> v;
    int hour;   double temperature;

    while (is >> hour >> temperature){
        v.push_back(Temperature{hour, temperature});
    }
    for (Temperature t:v) {
        cout << t.hour << "시의 온도는 " << t.temperature << endl;
    }
}

 

 

 

 

 

※ 저장된 txt파일을 읽어 앞에 숫자를 붙인 후 출력파일에 기록해보자.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

cf-1. 절대경로로 File I/O, File Open 하는법

1. Edit Configurations를 클릭한다.
Working directory를 원하는 절대경로로 지정해준다. (원상복구 시키고 싶으면 비워주면 됨)

 

 

 

cf-2) 상대경로로 txt파일을 내부에 만들고 사용하기

+ Recent posts