开发者

In memory Binary Search Vs. Disk based Binary Search

In this program, I am reading "key.pc.db" file and printing its mid value.

#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
using namespace std;
int main( int argc, char *argv[] )
{
        ifstream  fp;     
        int mval;
        int sizek;
        struct stat filek;
        int min, max, mid;
        if(stat("key.pc.db", &filek) ==0 )
             sizek=filek.st_size;
        sizek=sizek/sizeof(int);
        min=0;
        max=sizek-1;
        mid=(min+max)/2;    
        printf("mid %d ",mid);
        fp.open( "key.pc.db", ios::in | ios::binary ); 
        fp.seekg(mid, ios::beg);
        fp.read( (char *) &mval, (int) sizeof( int ) );
        printf("%d mval ", mval);
        getch();
        return 1;
}

In this program also I am reading the same file but I am storing the value of the file in an array and then printing the mid value. The mid index for both the program shows the same but the value comes out to be different. Why so?

#include <开发者_StackOverflow;fstream>
#include <conio.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
using namespace std;
int main( int argc, char *argv[] )
{
        ifstream  fp;     
        int index;
        int sizek;
        int kval;
        struct stat filek;
        int min, max, mid;
        int i=0;
        if(stat("key.pc.db", &filek) ==0 )
             sizek=filek.st_size;
        sizek=sizek/sizeof(int);
        int k[sizek];
        fp.open( "key.pc.db", ios::in | ios::binary );  
        fp.read( (char *) &kval, (int) sizeof( int ) );
        while( !fp.eof() ) 
         {
               k[i++]=kval;
               fp.read( (char *) &kval, (int) sizeof( int ) );
         }
        min=0;
        max=sizek-1;
        mid=(min+max)/2;
        printf(" index %d ", mid);
        printf(" kmid %d ", k[mid]);
        getch();
        return 1;
}


You're seeking to the wrong point in the file in the first case. You should be seeking to mid*sizeof(int) rather than mid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜