1. 磁盤模式查詢數據:ios
#include <iostream> #include <fstream> #include <memory> #include <cstdlib> #include <string> #include <cstring> using namespace std; //磁盤模式查詢數據 void main() { ifstream fin(R"(C:\00-數據\kf.txt)"); ofstream fout(R"(C:\res.txt)"); if (!fin || !fout) { cout << "文件打開失敗!" << endl; return; } char name[300]{ 0 }; cin >> name; //輸入要查詢的數據 while (!fin.eof()) //沒有到文件末尾就繼續 { char str[500]{ 0 }; fin.getline(str, 500);//讀取一行 char *p = strstr(str, name); if (p != nullptr) { cout << str << endl;//打印到屏幕 fout << str << endl;//寫入到文件 } } fin.close(); fout.close();//關閉文件 cin.get(); }
2. 內存模式查詢數據:數組
#include <iostream> //輸入輸出 #include <fstream> //文件流 #include <string> //字符串 #include <cstring> //C 字符串 #include <vector> //動態數組 #include <list> //C++效率低點,STL中有不少優化 using namespace std; list<string> g_all; //動態數組,每個元素都是字符串 list比vector快不少 //載入內存 void loadmem() { ifstream fin(R"(C:\00-數據\kf.txt)"); if (!fin) { cout << "文件打開失敗!" << endl; return; } while (!fin.eof()) //沒有到文件末尾就繼續 { char str[500]{ 0 }; fin.getline(str, 500); //讀取 string putstr; putstr += str; //生成C++字符串 g_all.push_back(putstr); } fin.close();//關閉文件 } //查詢 void search() { while (1) { cout << "輸入要查詢的數據:" << endl; string str; cin >> str; for (auto i : g_all) { int pos = i.find(str, 0);//查找 if (pos!=-1)//找到 { cout << i << endl; } } } } void main() { loadmem(); //載入內存 search();//查找 cin.get(); }