Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:








C
//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 ;
			}
		}
	}
}
Posted
Updated 24-May-10 6:09am
v4
Comments
Moak 21-May-10 10:17am    
Updated subject and tags, hope this is what you are looking for.

1 solution

Please add some comments to understand your logic,
I think binary search logic is correct( assuem that records are stored in the order of family ).

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900