개발/C++
13장 파일 입력과 출력
민돌이2
2019. 5. 21. 03:28
한성대학교 김설현교수님 강의내용을 바탕으로 작성함
파일 입출력
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()함수를 사용해 객체를 반드시 닫아야 에러발생을 예방할 수 있다.
파일로부터 데이터 읽기
#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이다.
#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