📝 파일 모드
- 파일 입출력에 대한 구체적인 작업 행태에 대한 지정
- 파일에서 읽을 작업을 할 것인지, 쓰기 작업을 할 것인지
- 기존 파일의 데이터를 모두 지우고 쓸 것인지, 파일의 끝 부분에 쓸 것인지
- 텍스트 I/O 방식인지 바이너리 I/O 방식인지
- 파일 모드 지정 파일 열 때
- open("파일이름", 파일모드)
- ifstream("파일이름", 파일모드)
- ofsream("파일이름", 파일모드)
✏️ 파일 읽기 예제
#include <iostream>
#include <fstream>
using namespace std;
int main() {
const char* file = "c:\\windows\\system.ini";
ifstream fin(file);
if (!fin) {
cout << file << "열기 오류" << endl;
return 0;
}
int count = 0;
int c;
while ((c=fin.get()) != EOF)
{
cout << (char)c;
count++;
}
cout << "읽은 바이트 수는" << count << endl;
fin.close();
}
📝 파일의 끝 EOF
- 파일의 끝에서 읽기를 시도하면 get()는 EOF(-1)을 반환한다.
✏️ 텍스트 파일의 라인 읽기
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void fileRead(vector<string>& v, ifstream& fin) {
string line;
while (getline(fin,line))
{
v.push_back(line);
}
}
void search(vector<string>& v, string word) {
for (int i = 0; i < v.size(); i++) {
int index = v[i].find(word);
if (index != -1) {
cout << v[i] << endl;
}
}
}
int main() {
ifstream fin("c:\\temp\\student.txt");
vector<string> wordVector;
if (!fin) {
cout << "파일 열기 실패" << endl;
return 0;
}
fileRead(wordVector, fin);
fin.close();
cout << "student.txt 파일을 읽었습니다." << endl;
while (true)
{
cout << "검색할 단어를 입력하세요 >>";
string word;
getline(cin, word);
if (word == "exit") { break; }
search(wordVector, word);
}
cout << "프로그램 종료";
}