1. 程式人生 > >磁碟/記憶體模式查詢資料

磁碟/記憶體模式查詢資料

1. 磁碟模式查詢資料:

#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(); }