목차
- fstream 라이브러리 소개/구문
- fstream 라이브러리 소속 3개의 클래스
- 파일 생성/쓰기/읽기
fstream 라이브러리 소개/구문
fstream 라이브러리 사용하면, 파일 제어 가능.
※ 표준 <iostream>, <fstream> 헤더 파일 둘 다 인클루드 필요.
[구문]
#include <iostream>
#include <fstream>
fstream 라이브러리 소속 3개의 클래스
ofstream
파일 생성/쓰기
ifstream
파일 읽기.
fstream
ofstream과 ifstream의 조합.
즉, 파일 생성/쓰기/읽기.
파일 생성/쓰기/읽기
파일명: main.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
// 파일 생성
ofstream HzWriteFile("hz.txt");
// 파일 쓰기
HzWriteFile << "홈짱닷컴 Homzzang.com";
// 파일 닫기
HzWriteFile.close();
// 파일 내용 변수 선언
string hzText;
// 파일 읽기
ifstream HzReadFile("hz.txt");
// 파일을 라인 단위로 읽기
while (getline (HzReadFile, hzText)) {
cout << hzText; // 파일 라인 단위로 출력
}
// 파일 닫기
HzReadFile.close();
}
결과값: 홈짱닷컴 Homzzang.com
PS. 파일 생성/쓰기
※ ofstream (또는, fstream) 클래스 이용.
※ << 삽입연산자 이용해 내용 입력.
※ 불필요한 메모리 공간 청소 위해, close() 메서드로 닫음.
PS2. 파일 읽기.
※ ifstream (또는, fstream) 클래스 이용.
※ while 반복문과 getline() 메서드 이용해 파일을 라인 단위로 읽기.
※ getline() 메서드는 ifstream 클래스에 속함.
※ 불필요한 메모리 공간 청소 위해, close() 메서드로 닫음.
※ HzWriteFile, HzReadFile 명칭은 임의 명명.
최신댓글