文件流类
ifstream(读操作)
ofstream(写操作)
fstream(读写操作)
写文件
1 2 3 4 5
| #include<fstream> ofstream ofs; ofs.open("文件路径",打开方式); ofs<<"..."; ofs.close();
|
打开方式 |
解释 |
ios::in |
为读文件打开 |
ios:out |
为写文件打开 |
ios::ate |
初始位置在文件尾 |
ios:app |
追加方式写文件 |
ios:trunc |
如果文件存在先删除,再创建 |
ios::binary |
二进制方式 |
读文件
1 2 3 4 5 6 7 8 9 10
| #include<fstream> ifstream ifs; ifs.open("文件路径",打开方式); char buffer[1024]; while(ifs.read(buffer, sizeof(buffer) - 1)){ buffer[ifs.gcount()]='\0'; cout<<buffer; memset(buffer, 0, sizeof(buffer)); } ifs.close();
|
检索文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std;
vector<string> findSentencesWithKeyword(const string& filename, const string& keyword) { vector<string> sentences; ifstream infile(filename); if (!infile) { cerr << "无法打开文件: " << filename << endl; return sentences; }
string line; while (getline(infile, line)) { istringstream iss(line); string sentence; while (getline(iss, sentence, '.')) { // 按句号分割句子 if (sentence.find(keyword) != string::npos) { sentences.push_back(sentence + "."); } } }
infile.close(); return sentences; }
int main() { string filename; cout << "请输入文件名: "; cin >> filename;
string keyword; cout << "请输入关键词: "; cin >> keyword;
vector<string> sentences = findSentencesWithKeyword(filename, keyword);
if (sentences.empty()) { cout << "未找到包含关键词的句子。" << endl; return 0; }
cout << "按回车键显示下一个包含关键词的句子,输入 'q' 退出。" << endl; char input; for (size_t i = 0; i < sentences.size(); ++i) { cin.get(input); // 等待用户输入 if (input == 'q') { break; } cout << "找到句子: " << sentences[i] << endl; }
return 0; }
|