본문 바로가기
개발/C++

13장 파일 입력과 출력

by 민돌이2 2019. 5. 21.

한성대학교 김설현교수님 강의내용을 바탕으로 작성함

 

파일 입출력

ifstream, ofstrea, fstream클래스가 제공되면 <fstream>헤더파일에 정의되어있다.

cin과 cout도 표준입출력을 담당하는 스트림 객체이다.

ofstream : 데이터 쓰기

ifstream : 데이터 읽기

 

파일로 데이터 쓰기

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

int main() 
{
	ofstream output;
	output.open("scores.txt"); //파일 생성

	output << "John" << " " << "T" << " " << "Smith" << " " << 90 << endl;
	output << "Eric" << " " << "K" << " " << "Jones" << " " << 85 << endl;

	output.close(); //파일 닫기
	cout << "Done" << endl;

	system("pause");
	return 0;
}

close()함수를 사용해 객체를 반드시 닫아야 에러발생을 예방할 수 있다.

실행 결과

 

파일로부터 데이터 읽기

읽을 txt파일

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

int main() 
{
	ifstream input("scores.txt"); //존재하는 파일 읽기

	string firstName;
	char mi;
	string lastName;
	int score;

	input >> firstName >> mi >> lastName >> score; //데이터를 순서대로 저장
	cout << firstName << " " << mi << " " << lastName << " " << score << endl;

	input >> firstName >> mi >> lastName >> score;
	cout << firstName << " " << mi << " " << lastName << " " << score << endl;

	input.close();
	cout << "Done" << endl;

	system("pause");
	return 0;
}

실행 결과

데이터를 올바르게 읽기 위해서 데이터가 어떻게 저장 되어 있는 지 정확히 알아야 한다.

ex)변수종류

 

파일존재 여부 테스트

ifstrem input("score.txt");

if (input.fail()) 
{
	cout << "File does not exist" << endl;
	retrun 0;
}

 

파일의끝 테스트

ifstream input("score.txt");
double number;

while (!input.eof()) //eof : 파일의 끝
{ 
	input >> number;
	cout << number << " ";
}

 

getline( )함수

>>(스트림 추출 연산자)를 사용하여 데이터를 읽으면 공백이 있는 문자열은 읽어 올 수 없어,getline()함수를 이용한다.

구분문자(delimit character)나 파일의 끝(eof:end-of-file)표시를 만나면 문자읽기를 멈춘다.

구분문자는 읽기는 하지만 저장하지는 않으며, 기본값은 \n이다.

읽을 txt파일

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

int main() 
{
	ifstream input("state.txt"); //파일열기(미리 만들어져 있어야 함)

	if (input.fail()) // 파일 존재하는지 확인 함
	{ 
		cout << "File does not exist" << endl;
		cout << "Exit program" << endl;
		return 0;
	}

	string city;
	while (!input.eof()) //eof() 만날 때 까지 파일 읽음
	{ 
		getline(input, city);
		cout << city << endl;
	}
	input.close();

	system("pause");
	return 0;
}

실행 결과

728x90

'개발 > C++' 카테고리의 다른 글

C++ 클래스 메모리 할당 정리  (0) 2021.12.27
16장 예외처리  (0) 2021.12.09
15장 상속과 다형성  (0) 2021.12.09
14장 연산자 오버로딩  (0) 2021.12.09
12장 템플릿, 벡터, 스택  (0) 2019.05.13
11장 포인터와 동적 메모리 관리(후)  (0) 2019.05.09
11장 포인터와 동적 메모리 관리(전)  (0) 2019.05.08
10장 객체 지향 개념  (0) 2019.02.11

댓글