본문 바로가기
개인 공부/C++

[C++] 텍스트(.txt)파일 읽기 및 쓰기 | ifstream | ofstream | 간단설명

by 그레이슨킴 2021. 6. 21.

□ 텍스트 파일 읽기: ifstream

예제부터 보시죠.

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

int main() {
	string line;
	ifstream file("example.txt"); // example.txt 파일을 연다. 없으면 생성. 
	if(file.is_open()){
		while(getline(file, line)) {
			cout << line << endl;
		}
		file.close(); // 열었떤 파일을 닫는다. 
	} else {
		cout << "Unable to open file";
		return 1;
	}
	return 0;
} 

example.txt 내용
출력

먼저 파일 입출력 함수를 사용하기 위해선 fstream 헤더를 포함시켜야 합니다.
#include <fstream>

ifstream의 형태는 다음과 같습니다.
ifstream 이름(파일경로);

파일을 연 후에는 if문.is_open() 함수로 에러 처리를 해 줍니다.
.is_open() 함수는 이름에서도 알 수 있듯이 파일이 정상적으로 열렸는지 확인하는 함수입니다. 정상적으로 열렸다면 true를 그렇지 않다면 false를 반환합니다.

getline(이름, string) 함수는 열었던 텍스트 파일을 한 줄씩 읽어와 string 형태로 저장합니다.

열었던 파일은 이름.close() 함수로 반드시 닫아줘야 합니다.


□ 텍스트 파일 쓰기: ofstream

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

int main() {
	string line;
	ofstream file("output.txt");
	if(file.is_open()) {
		file << "This is the first line.\n";
		file << "this is the second line.\n";
		file.close();
	} else {
		cout << "error" << endl;
		return 1;
	}
	return 0;
}

 

실행 화면
실행함으로써 생성된 output.txt

ifstream 과 열고 닫는 방법은 같습니다.

이름 << 내용; 과 같은 형태로 파일에 데이터를 쓸 수 있습니다.

댓글