※ 스트림(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 소멸자가 파일을 닫는다.
}
※ 파일 쓰기
※ 파일 모드
※ 파일에서 읽은 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 하는법
cf-2) 상대경로로 txt파일을 내부에 만들고 사용하기
'C | C++ > C++' 카테고리의 다른 글
this.code(12)_ auto 키워드와 decltype & 범위기반 for문 (★★★★) (0) | 2022.10.29 |
---|---|
this.code(11)_ Exception Handling (예외 처리), Exception 클래스, noexcept (0) | 2022.10.29 |
this.code(10)_ template (★★★★★)과 함수객체(functor) (0) | 2022.10.29 |
this.code(9)_ smart pointer & type casting_ part 2. (0) | 2022.10.29 |
★this.code(8)_ type casting_ part 1. cast operator (★★★) (0) | 2022.10.29 |