#include <cstdlib>
#include <iostream>
#include <stdio.h>
using namespace std;
#define MAX_MESH 39824
#define MAX_READ 128
struct sMesh
{
string text;
fpos_t addr; } mesh[MAX_MESH];
bool read_line( FILE *f );
bool read_line_seek( FILE *f, const fpos_t *pos, sMesh& m );
int last_mesh; int compare(const void *m1, const void *m2)
{
struct sMesh *mi1 = (struct sMesh *) m1;
struct sMesh *mi2 = (struct sMesh *) m2;
return strcmp(mi1->text.c_str(), mi2->text.c_str());
}
int main()
{
FILE *x;
x = fopen("mdata","r");
while ( last_mesh < MAX_MESH )
{
if ( read_line( x ) == false )
break;
}
qsort( mesh, last_mesh, sizeof(struct sMesh), compare);
char txt[MAX_READ];
cout << "\n\nInput text to find:\n\n>";
cin.getline(txt, MAX_READ);
while ( 1 )
{
if ( !strcmp(txt,"quit") || txt[0] == 'q' || txt[0] == '\0' )
break;
struct sMesh k, *res = NULL;
k.text = txt;
res = (sMesh *) bsearch(&k, mesh, last_mesh, sizeof(struct sMesh), compare);
if (res == NULL)
cout << "No match for '" << txt << "'\n\n";
else
{
read_line_seek( x, &res->addr, k );
cout << "Match (" << txt << ") -> text == '" << k.text << "'; addr == " << k.addr << endl << endl;
}
cout << "> ";
cin.getline(txt, MAX_READ);
}
return EXIT_SUCCESS;
}
bool read_line_seek( FILE *f, const fpos_t *pos, sMesh& m )
{
char buf[MAX_READ]; string s;
if ( !f )
return false;
m.text = "";
m.addr = -1;
if ( fsetpos(f, pos) != 0 )
return false;
if ( fgets(buf,MAX_READ,f) == NULL )
return false;
buf[strlen(buf)-1]='\0'; s = buf;
while ( s[0] != ';' )
s.erase(0,1);
s.erase(0,2);
m.addr = *pos;
m.text = s;
return true;
}
bool read_line( FILE *f )
{
fpos_t pos; char buf[MAX_READ]; string s;
if ( !f )
return false;
if ( fgetpos( f, &pos ) != 0 )
return false;
if ( fgets(buf,MAX_READ,f) == NULL )
return false;
buf[strlen(buf)-1]='\0'; s = buf;
while ( s[0] != ';' )
s.erase(0,1);
s.erase(0,2);
mesh[last_mesh].text = s;
mesh[last_mesh++].addr = pos;
return true;
}