파일 입출력은 fstream의 ifstream 을 이용하여 파일을 입력하고 ofstream 을 이용하여 파일을 출력합니다.
파일 읽기
- ifstream 객체명("파일명");
파일 쓰기
- ofstream 객체명("파일명");
ifstream 함수
함수 | 설명 |
close | 파일 닫기 |
is_open | 파일이 열러 있는지 확인 |
open | 파일 열기 |
rdbuf | 저장된 스트림 버퍼 주소를 반환 |
swap | 이 basic_ifstream의 콘텐츠를 제공된 basic_ifstream의 콘텐츠로 교환 |
ofstream 함수
함수 | 설명 |
close | 파일 닫기 |
is_open | 파일이 열러 있는지 확인 |
open | 파일 열기 |
rdbuf | 저장된 스트림 버퍼 주소를 반환 |
swap | 이 basic_ifstream의 콘텐츠를 제공된 basic_ifstream의 콘텐츠로 교환 |
open()함수 모드
-
app - 출력하는 데이터가 파일 끝에 기록
-
ate - 파일을 열면서 파일 포인터를 끝으로 이동
-
binary - 바이너리 모드로 오픈
-
in - 읽기모드로 오픈
-
out - 삽입모드로 파일를 오픈
-
trunc - 개체가 생성 될 때 기존 파일의 내용을 삭제하고 다시 만듬
파일에 저장하고 파일에서 읽어오기
#include <iostream> #include <fstream>
using namespace std;
void main() { int s, sum = 0; ofstream fout("output.txt"); // 파일입력쓰기 ifstream fin("output.txt"); //파일출력읽기
for (int i = 1; i <= 10; i++) { fout << i << endl; }
while (1) { fin >> s; if (fin.eof()) break
sum += s; cout << s << " : " << sum << endl; }
fout.close(); fin.close(); } |
파일을 읽고 파일에 저장하기
#include <iostream> #include <fstream>
using namespace std;
void main() { int s, sum = 0; char arr[100]; ifstream fin("input.txt"); //파일출력읽기 ofstream fout("output.txt"); // 파일입력쓰기
while (!fin.eof()) { fin.getline(arr, 100); // 파일읽기 cout << arr << endl;
fout << arr << endl; // 파일쓰기 }
fin.close(); fout.close(); } |
#include <iostream> #include <fstream> #include <string> #include <vector>
using namespace std;
class Student { private: char name[10], dept[20], sid[11], address[50]; public: void inputData() { ofstream fout; fout.open("student.txt", ios::out | ios::app);
while (true) { cout << "이름 " cin.getline(name, 10); if (strcmp(name, "exit") == 0) { break // while문종료 } cout << "학과 " cin.getline(dept, 20); cout << "학번 " cin.getline(sid, 11); // 한줄입력받아서id에저장 cout << "주소 " cin.getline(address, 50);
if (!fout) { cout << "파일오픈에러" return; }
/* 파일쓰기 */ fout << name << endl; fout << dept << endl; fout << sid << endl; fout << address << endl; } /* 파일닫기/ fout.close(); }
void outputData() { /* 파일오픈 읽기/ ifstream fin("student.txt"); if (!fin) { cout << "파일오픈에러 << endl; return' }
/* 파일에서한글자씩of일때까지읽기/ /* int c = 0; while ((c = fin.get()) != -1) { cout << (char)c; } */ /* 파일에서한줄씩of일때까지읽기/ char buf[100]; while (true) { fin.getline(buf, 100); if (fin.eof()) { break; } cout << buf << endl; } /* 파일닫기/ fin.close(); } |
void search() { vector<string> wordVector; /* 파일오픈 읽기/ ifstream fin("student.txt"); if (!fin) { cout << "파일오픈에러 << endl; return; } string line; while (true) { getline(fin, line); if (fin.eof()) { break; } wordVector.push_back(line); } /* 파일닫기/ fin.close();
while (true) { cout << "검색할단어를입력하세요>" string word; getline(cin, word); if (word == "exit") { break; } /* 단어검색/ for (int i = 0; i < wordVector.size(); i++) { int index = wordVector[i].find(word); if (index != -1) { cout << wordVector[i] << endl; } } } }
int main() { //인스턴스생성 Student hongildong; hongildong.inputData(); //데이터입력 hongildong.outputData(); //데이터출력 hongildong.search();//검색
return 0; } ![]() |
메인 함수에서 파일 처리를 하지 않고, 클래스에서 그 파일 스트림을 받아서 처리하기.
#include <iostream> #include <fstream>
#define MAX_SIZE 1000 using namespace std;
char line[MAX_SIZE];
class fileInput { private: int lineNum; public: fileInput(); void input(ifstream& infile, ofstream& outfile); void showLine(); }; fileInput::fileInput() { lineNum = 0; } void fileInput::input(ifstream& infile, ofstream& outfile) { while (!infile.eof()) { infile.getline(line, MAX_SIZE); lineNum++; cout << "파일읽기 " << line << endl; outfile << line << endl; } } void fileInput::showLine() { cout << endl; cout << "입력파일의총라인수 " << lineNum << endl; cout << endl; }
int main() { ifstream infile("input.txt"); ofstream outfile("output.txt");
fileInput fl; // 파일스트림을인자값으로넘긴다 fl.input(infile, outfile); fl.showLine(); infile.close(); outfile.close();
ifstream infile2("output.txt"); while (!infile2.eof()) { infile2.getline(line, MAX_SIZE); cout << line << endl; }
infile.close(); return 0; } |
![]() |
주소록 파일입출력
#include <iostream> #include <fstream> using namespace std;
class Address { private: char processNumber[10]; // Menu번호를저장하는변수 int quit; // 종료여부를판단하기위한변수1이면종료
public: void intro(); // 초기화면을출력하는함수 void seletMenu(); // 메뉴선택을요구하는함수 void inputPN(); // 메뉴번호를입력받아처리하는함수 void readAddress(); // 주소록을읽는함수 void writeAddress(); // 주소록에쓰는함수 void searchAddress(); // 주소록을검색하는함수 int checkQuit(); // quit의값을읽는함수 void ProcessQuit(); // 프로그램을종료하기위한함수
/* 초기화면을출력하는함수*/ void Address::intro() { /* 프로그램제목을출력합니다 */ cout << "* 나의주소록 * \n" cout << "************************* \n" }
/* 메뉴선택을요구하는함수*/ void Address::seletMenu() { cout << "\n" //한줄띄웁니다 cout << "====MENU==== \n" cout << "목록보기 1 \n" cout << "입력하기 2 \n" cout << "검색하기 3 \n" cout << "종료하기 4 \n" cout << "============ \n" cout << "MENU 번호를선택하세요 " }
/* 메뉴번호를입력받아처리하는함수*/ void Address::inputPN() { cin.getline(processNumber, sizeof(processNumber));
/* 사용자의입력이잘못되면반복해서다시받는다 */ while ((atoi(processNumber) != 1) && (atoi(processNumber) != 2) && (atoi(processNumber) != 3) && (atoi(processNumber) != 4)) { seletMenu(); cin.getline(processNumber, sizeof(processNumber)); }
if (atoi(processNumber) == 1) readAddress(); else if (atoi(processNumber) == 2) writeAddress(); else if (atoi(processNumber) == 3) searchAddress(); else if (atoi(processNumber) == 4) ProcessQuit(); }
/* 주소록을읽는함수*/ void Address::readAddress() { char list[300]; ifstream AddressList("주소록txt"); if (!AddressList) { cout << "주소록파일을열수없습니다 \n" quit = 1; } else { cout << "\n" //한줄띄웁니다 cout << ">>>> 주소록목록<<< \n"
while (!AddressList.eof()) { AddressList.getline(list, sizeof(list)); cout << list << "\n" } } AddressList.close(); // 파일닫기 } /* 주소록에쓰는함수*/ void Address::writeAddress() { ofstream wAddress("주소록txt", ios::app);
/* 파일을여는데실패하면프로그램을종료합니다 */ if (!wAddress) { cout << "주소록파일을열수없습니다 \n" quit = 1; } else { char name[20]; //이름 char address[100]; //주소 char handphone[20]; //핸드폰
cout << "\n" cout << "이름입력 " cin.getline(name, sizeof(name)); cout << "주소입력 " cin.getline(address, sizeof(address)); cout << "핸드폰번호입력 " cin.getline(handphone, sizeof(handphone));
wAddress << name << ", " wAddress << address << ", " wAddress << handphone << "\n"
wAddress.close(); // 파일을닫습니다 } } /* 주소록을검색하는함수*/ void Address::searchAddress() { char* searchResult; // 검색결과를저장하는변수 int findCounter = 0; //키워드검색시발견횟수를저장하기위한변수 ifstream sAddress("주소록txt"); if (!sAddress) { cout << "주소록파일을열수없습니다 \n" quit = 1; } else { char keyWord[30]; // 검색어를저장하는변수 cout << "\n" // 한줄띄웁니다 cout << "검색어를입력하세요 " cin.getline(keyWord, sizeof(keyWord)); cout << "\n" // 한줄띄웁니다 cout << ">>>> 검색결과<<< \n"
while (sAddress) { char sAddressList[300]; sAddress.getline(sAddressList, sizeof(sAddressList));
searchResult = strstr(sAddressList, keyWord);
/* 검색어가발견되면해당행을출력한다 */ if (searchResult) { cout << sAddressList << "\n" ++findCounter; // 발견횟수증가 } }
/* 검색자료가없습니다 출력하기*/ if (findCounter == 0) // 발견횟수가이면검색자료가없습니다 { cout << "검색자료가없습니다 \n" } sAddress.close(); } }
/* quit의값을읽는함수*/ int Address::checkQuit() { return quit; }
/* 프로그램을종료하기위한함수*/ void Address::ProcessQuit() { cout << "... 프로그램이종료되었습니다\n"
quit = 1; }
/* main()함수입니다*/ int main() { Address myAddress; // Address클래스를이용해서객체를생성합니다 myAddress.intro(); // 주소록초기화면을출력합니다
while (myAddress.checkQuit() != 1) // 종료조건이아닌경우반복합니다 { myAddress.seletMenu(); // 사용자가enu를선택하도록합니다 myAddress.inputPN(); // 사용자가선택한enu에따라처리합니다 } return 0; } |
![]() ![]() |
학생 성적 입/출력프로그램
#include <iostream> #include <fstream> using namespace std; class student { private: char num[5]; int quit; int kor, math, eng; int sum; double avg; public: void intro(); // 시작화면 함수 void menu(); // 메뉴항목을 보여주는함수 void select(); // 메뉴 번호를 입력받는 함수 void write(); // 입력받아 파일에 저장하는 함수 void showlist(); // 파일에서 읽어와 보여주는 함수 void search(); // 검색하는 함수 int checkQuit(); // quit값을 읽는 함수 void processquit(); // 프로그램 종료 함수 void score(); // 과목입력과 합계/평균구하는 함수 }; void student::intro() { cout << "**** 학생 성적 입/출력 *****" << endl; } void student::menu() { cout << "===MENU===" << endl; cout << "1. 입력하기" << endl; cout << "2. 리스트보기" << endl; cout << "3. 검색하기" << endl; cout << "4. 종료하기" << endl; cout << "=========" << endl; } void student::select() { cout << "[메뉴선택] : "; cin.getline(num, sizeof(num)); while ((atoi(num) != 1) && (atoi(num) != 2) && (atoi(num) != 3) && (atoi(num) != 4)) { cin.getline(num, sizeof(num)); } if (atoi(num) == 1) write(); else if (atoi(num) == 2) showlist(); else if (atoi(num) == 3) search(); else if (atoi(num) == 4) processquit(); } void student::write() { ofstream wAddress("list.txt", ios::out|ios::app); if (!wAddress) { cout << "파일을 열 수 없습니다.\n"; quit = 1; } else { char name[10]; char stdnum[10];
cout << "\n"; cout << "이름입력 : "; cin.getline(name, sizeof(name)); cout << "학번입력 : "; cin.getline(stdnum,sizeof(stdnum)); score(); wAddress << name << ","; wAddress << stdnum << ","; wAddress << "(국어):"<<kor << ","; wAddress << "(수학):"<< math << ","; wAddress << "(영어):" << eng << ","; wAddress <<"(합계)"<< sum << ","; wAddress << "(평균)"<<avg; wAddress << "\n"; wAddress.close(); } } void student::score() { // 과목입력과 합계/평균구하는 함수 cout << "국어:"; cin >> kor; cout << "수학:"; cin >> math; cout << "영어:"; cin >> eng; sum = kor+math+eng; avg = (double)sum/3; } void student::showlist() { char list[300]; ifstream AddressList("list.txt"); if (!AddressList) { cout << "파일을 열 수 없습니다\n"; quit = 1; } else { cout << "\n"; cout << "----리스트보기-----" << endl; while (!AddressList.eof()) { AddressList.getline(list, sizeof(list)); cout << list << "\n"; } } AddressList.close(); } void student::search() { char *searchResult; int findCounter = 0; ifstream sAddress("A.txt"); if (!sAddress) { cout << "파일을 열 수 없습니다.\n"; quit = 1; } else{ char keyWord[30]; cout << "\n"; cout << "검색어를 입력하세요 "; cin.getline(keyWord, sizeof(keyWord)); cout << "\n"; cout << "-----검색결과-----" << endl; while (sAddress) { char sAddressList[300]; sAddress.getline(sAddressList, sizeof(sAddressList)); searchResult = strstr(sAddressList, keyWord); if (searchResult) { cout << sAddressList << "\n"; ++findCounter; } } if (findCounter == 0) cout << "검색자료가 없습니다...\n"; sAddress.close(); } } int student::checkQuit() { return quit; } void student::processquit() { cout << "..프로그램 종료\n"; quit = 1; } int main() { student mystudent; mystudent.intro(); while (mystudent.checkQuit() != 1) { mystudent.menu(); mystudent.select(); } return 0; } |