如何实现文件搜索 [英] How to implement a file search
本文介绍了如何实现文件搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个程序来读取文件并在其中进行二进制搜索.我不知道此代码是否正确,请检查一下:
I want to write a program to read a file and binary search in it. I don''t know if this code is correct or not, please check it:
//size of record = 100 b
//size of blonck = 4 kb
struct record{
char name [26] ;
char family[30] ;
char stu_no [20] ;
char mobil [20] ;
record * pnext ;
};
record search ( record pdata )
{
char item [30];
char x ;
fstream file ;
file.open ( "file2.dat" ) ;
int med ;
int low = 0 ;
//counterb is number of blonck
int hight = counterb - 1 ;
while ( low <=hight )
{
med = ( low + hight )/2 ;
file.seekp (4096*med , ios::beg ) ;
for ( int i = 0 ; i < 30 ; i++ )
{
file.read ( &x , 1 ) ;
item[i] = x ;
}
for ( int i = 0 ; i < 30 ; i++ )
{
int y = strcmp ( item , pdata.family ) ;
if ( y == 0 )
{
file >> pdata.family >> pdata .name >> pdata .mobil >> pdata .stu_no ;
return pdata ;
}
if ( y < 0 )
{
file.seekp (-4096 , ios::beg ) ;
for ( int i = 0 ; i < 30 ; i++ )
{
file.read ( &x , 1 ) ;
item[i] = x ;
}
y = strcmp ( item , pdata.family ) ;
med = (low + med -1)/2 ;
}
if ( y > 0 )
{
file.seekp (counterr*100 , ios::beg ) ;
for ( int i = 0 ; i < 30 ; i++ )
{
file.read ( &x , 1 ) ;
item[i] = x ;
}
y = strcmp ( item , pdata.family ) ;
med = (hight + med +1)/2 ;
}
}
}
}
推荐答案
请添加一些注释以了解您的逻辑,
我认为二进制搜索逻辑是正确的(假设记录按family
的顺序存储).
我认为读取文件时可能会出现一些错误,最好读取写入记录块本身,否则将无法获得预期的结果.
Please add some comments to understand your logic,
I think binary search logic is correct( assuem that records are stored in the order offamily
).
I think there may be some error in reading file, it is better to read write the record block itself otherwise it will not get expected result.
这篇关于如何实现文件搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文