我致力于使用可扩展哈希来更快地找到查询。我的代码是这个步骤:1)读取主文本文件(hudge文件4 GiB)文件是这样的:
12435 alex romero
13452 jack robert
13485 marya car
45132 gun tribble
...
用户想知道例如密钥 12435 与什么有关?(答案:alex romero)
2)为文件中的键创建一个哈希表(我的意思是12435,13452,13485,...),我将此表动态保存在硬盘中一些名为:0.txt,1.txt,2的文本文件中。 txt 和....
3)当用户对程序进行查询时,程序必须对其值计算散列函数并找到必须读取的文件,这样才能更快地找到结果。
我有一个功能:
#define LIMIT 7
void writeInFile(int key , const char* charPos ){
int remainder = key%(LIMIT*LIMIT);
string myFileName;
ostringstream convert;
convert << remainder ;
myFileName = convert.str();
myFileName += ".txt";
FILE *my_file;
my_file = fopen(myFileName.c_str() ,"a");
fputs("\n" ,my_file);
fputs(charPos , my_file);
//fclose(my_file);
}
我想知道当我使用时fclose
程序的速度会降低!然后我不在函数末尾使用它,但一个问题是当我多次使用此函数时我无法关闭它们然后我无法访问文件。我想创建一个文件的“列表”,我可以将它们的引用发送给函数,例如:FILE &* myFiles[]
或FILE &** myFiles
作为函数获取的第三个参数......但我看到了错误。我不知道它的语法如何。我的意思是一些语法,如:
void writeInFile(int key , const char* charPos , FILE &*myFiles[] ) // this makes error
我认为的另一种方法是我可以关闭那些现在无法访问的文件吗?或者我可以更改导致此问题的代码吗?
更新:这是我的完整代码
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <sstream>
#include <stdio.h>
#include <vector>
#define LIMIT 7
using namespace std;
void writeInFile(int key , const char* charPos ){
int remainder = key%(LIMIT*LIMIT);
string myFileName;
ostringstream convert;
convert << remainder ;
myFileName = convert.str();
myFileName += ".txt";
FILE *my_file;
my_file = fopen(myFileName.c_str() ,"a");
fputs("\n" ,my_file);
fputs(charPos ,my_file);
//fclose(my_file);
}
int main(){
string fileName;
cout << "hello, please inter your file destination : " ;
cin >> fileName;
ifstream myFile ;
myFile.open(fileName.c_str() ,ifstream::in |ifstream::binary);
cout << "building the hash,please wait";
string havij;//:D this is an unusable variable in this section :))
int current;
int index;
int isCout=0;
char buffer [10];
//FILE *my_file[49];
while(!myFile.eof()){
cout << isCout << endl;
isCout++;
index = myFile.tellg();
itoa(index , buffer ,10);
//cout << buffer << endl;
myFile >> current;
writeInFile(current ,buffer);
getline(myFile,havij);
}
myFile.close();
fstream test;
//for(int i =0 ; i<LIMIT*LIMIT-1 ; i++){
// fclose(my_file[i]);
//}
cout << endl << "static extensible hash structure builded please inter your query : " ;
int query;
cin >> query;
int remainder = query%(LIMIT*LIMIT);
string myFileName;
ostringstream convert;
convert << remainder ;
myFileName = convert.str();
myFileName += ".txt";
ifstream myFile2;
//myFile2 is now the files that create by program like : 12.txt ,25.txt ,....
myFile2.open(myFileName.c_str() , ifstream::in | ifstream::binary);
ifstream mainFile;
mainFile.open(fileName.c_str(), ifstream::in | ifstream::binary);
int position;
string wanted;
int tester;
while(!myFile2.eof()){
myFile2 >> position;
mainFile.seekg(position ,ios::beg);
mainFile >> tester;
if (tester == query ){
getline(mainFile ,wanted);
cout << "the result of the key " << tester << " is " << wanted << endl;
}
}
return 0;
}