编写C++程序从Linux命令行搜索索引文件

Writing a C++ Program to Search an Index File From the Linux Command Line

本文关键字:搜索 索引 文件 命令行 Linux C++ 程序 编写      更新时间:2023-10-16

我编写了一个程序,该程序读取数据文件并根据原始文件中的数据创建排序索引文件。然而,我应该写第二个程序,允许用户从Linux命令行搜索这个索引文件。例如,他们应该能够键入

search 12382 prog5.idx

并显示该记录的信息。我不知道如何做到这一点。

我已经写了代码来创建索引文件(作品):

#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;
class Record {
    string name;
    int code;
    double cost;
public:
    Record() {
    }
    Record(string tname,int tcode,double tcost) : name(tname),code(tcode),cost(tcost) { 
    }
    friend ostream& operator<< (ostream &os, const Record& r);
};
//print function
ostream& operator<< (ostream &os, const Record& r) {
    os << setw(10) << r.name << " " << setw(5) << r.code << " $"  << setw(10) << setprecision(2) << fixed << r.cost ;
    return os;
}
int main() {
    std::map<int, Record> myMap;
    ifstream data;
    size_t offset_count = 0;
    data.open("prog5.dat");
    ofstream outFile("prog5.idx", ios::out);
    //if file can't be opened, exit
    if(!data) {
        cerr << "Open Failure" << endl;
        exit(1);
    }
    std::string line;
    while (std::getline(data, line)) {
        stringstream ss(line);
        int key;
        string name;
        int code;
        double cost;
        if(ss >> key >> name >> code >> cost) {
            Record r(name,code,cost);
            myMap.insert( pair<int,Record>(key,r));
        }
        else {
             cout << "Error";
        }
    }
    // print what's stored in map
    for(std::map<int,Record>::iterator x = myMap.begin(); x!=myMap.end(); ++x) {
        cout << setw(10) << x->first << ": " << x->second << endl;
    }
}   

并在运行上述代码时获得以下输出:

     8:      blank     0 $      0.00
 12165:     Item16    30 $      7.69
 12345:     Item06    45 $     14.20
 12382:     Item09    62 $     41.37
 12434:     Item04    21 $     17.30
 16541:     Item12    21 $      9.99
 21212:     Itme31    19 $      8.35
 34186:     Item25    18 $     17.75
 41742:     Item14    55 $     12.36

以下是到目前为止我对第二个程序的了解:

#include <prog3.idx>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
    if(argc < 3) {
        std::cerr << "Too few arguments n";
        std::exit(EXIT_FAILURE);
    }
    int key = atoi(argv[1]);
    const char* filename = argv[2];
    ifstream input;
    input.open("prog5.idx");
}

但我不确定从那里去哪里。有人能帮我吗?

使用映射或多映射并在STL中查找。以索引为键,从剩余数据中生成一个数据类型。程序必须先读取整个文件,然后找到搜索到的索引。