c++ - 在 C++ 中创建和访问索引文件

标签 c++ linux file indexing

我应该读入一个包含固定长度记录和字段的数据文件,在内存中创建一个排序的索引列表,并将该列表保存到一个文件中。然后我要编写第二个程序,以交互方式(通过 Linux 命令行)获取一个键和索引文件名,打开并加载索引文件,使用索引表搜索给定的键,然后打开并返回正确的数据记录。

原始文件由带有键 (int)、名称(最多 8 个字符的字符串)、代码 (int) 和成本 (double) 的记录列表组成。

RRN(相对记录号)从 1 开始,RRN 为 0 表示只有第一个条目中的大小的虚拟记录。

这是我将要使用的数据文件。

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

在 Linux 中,执行应该以下列方式从命令行进行:

search 12382 prog5.idx

prog5.idx 是创建的索引文件。

我已经编写了一些代码,但到目前为止它所做的只是打开数据文件。

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream data;
    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);
    }
    else {
        cout << "File is open" << endl;
    }
}

“文件已打开”部分将被替换,一旦我弄清楚文件打开后该做什么,只是使用此消息来验证它正在打开文件。

我以前从未使用过这些类型的文件,所以不知道从这里去哪里。

最佳答案

我将为您提供第一个程序的可能朴素草稿,以便您了解总体思路:

#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

struct Record
{
    int key;
    char name[8];
    int code;
    double cost;
    size_t offset;
};

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);
    }
    else {
        cout << "File is open" << endl;
    }

    std::string line;
    while (std::getline(data, line))
    {
        std::istringstream iss(line);
        Record tmp;
        if (!(iss >> tmp.key >> tmp.name >> tmp.code >> tmp.cost))
        { 
            break; // error, do something
        }
        tmp.offset = offset_count;
        offset_count += sizeof(Record); 
        mymap.insert( pair<int,Record>(tmp.key,tmp) );
    }

    // Now you have all the info (and much more) you need in memory,
    // thus serialize the key and its position on a file 
    // So you have done the first part of the assignment

}

看例子here如果您不知道如何在 std:map 中进行迭代。

关于c++ - 在 C++ 中创建和访问索引文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26598218/

相关文章:

c++ - 有向图实现

linux - 删除名称中有空格的目录中最旧的文件

regex - Sed:如何替换在文件中找到特定模式后找到的字符串

安卓文件创建

file - 为什么我的 Go 程序使用打开文件的名称创建另一个 Go 进程,为什么它这么大?

c++ - 函数范围内的静态 constexpr - MSVC 的行为是编译器错误吗?

C++ 数组包装器

c - select() 在从客户端读取和接收数据时接受连接

python - 计算两个字符串日期之间的日期数并返回一个整数

c++ - boost aligned_allocator 对齐参数不影响实际对齐