gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:55:25 25 4
gpt4 key购买 nike

我应该读入一个包含固定长度记录和字段的数据文件,在内存中创建一个排序的索引列表,并将该列表保存到一个文件中。然后我要编写第二个程序,以交互方式(通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com