12장. 수업 코드
파일 입출력
#include <iostream>
#include <fstream>
using namespace std;
int main() {
char name[10], dept[20];
int sid;
cout << "name: ";
cin >> name;
cout << "sid: ";
cin >> sid;
cout << "dept: ";
cin >> dept;
ofstream fout("student.txt");
if(!fout) {
// 열기 실패한 경우
cout << "student.txt 파일을 열 수 없습니다." << endl;
return 0;
}
fout << name << endl;
fout << sid << endl;
fout << dept << endl;
cout << "파일 저장 완료" << endl;
fout.close();
}
C++
복사
cat student.txt
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
fin.open("student.txt");
if (!fin) {
cout << "Not open" << endl;
return 0;
}
char name[10], dept[20];
int sid;
fin >> name;
fin >> sid;
fin >> dept;
fin.close();
cout << name << sid << dept << endl;
}
C++
복사
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
string fname = "student.txt";
fin.open(fname);
if (!fin) {
cout << "Not open" << endl;
return 0;
}
char name[10], dept[20];
int sid;
fin >> name;
fin >> sid;
fin >> dept;
fin.close();
cout << name << sid << dept << endl;
string fName = "/etc/passwd";
ifstream fin2(fName);
if (!fin2) {
cout << "File Open Fail:" << fName << endl;
return 0;
}
int count = 0;
int c;
while((c = fin2.get()) != EOF) {
cout << (char)c;
count++;
}
cout << "Read Byte Count:" << count << endl;
fin2.close();
fstream fout2(fname, ios::out | ios::trunc);
if (!fout2) return 0;
fstream fin3(fName, ios::in);
while((c = fin3.get()) != EOF) {
fout2.put(c);
}
fin3.close();
fout2.close();
ifstream fin4;
fin4.open(fName);
if (!fin3) return 0;
string line;
while (getline(fin4, line))
cout << line << endl;
fin3.close();
}
C++
복사
단어 찾기
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void fileRead(vector<string>& v, ifstream &fin) {
string line;
while(getline(fin, line))
v.push_back(line);
cout << v.size() << "단어를 읽었습니다." << endl;
}
void search(vector<string>& v, string word) {
int count = 0;
for (auto it = v.begin(); it != v.end(); it++) {
int index = (*it).find(word);
if(index != -1) {
cout << *it << endl;
count++;
}
}
cout << "총 " << count << "개의 단어를 찾았습니다." << endl;
}
int main() {
string wordFileName = "words.txt";
ifstream fin(wordFileName);
if(!fin) {
cout << "파일 읽기 오류" << endl;
return 0;
}
vector<string> v;
fileRead(v, fin);
fin.close();
while(true) {
cout << "검색할 단어:";
string word;
getline(cin, word);
if(word == "exit") break;
search(v, word);
}
cout << "종료!" << endl;
}
C++
복사