磁盘/内存模式查询数据

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

猜你喜欢

转载自www.cnblogs.com/si-lei/p/9520948.html