开发者

Help using Strcmp() with a binary file

I have a function void display_a_student() which uses two binary files. Firstly a binary1.dat and and index.dat which contains the offset of each student added to the binary1.dat.

I am trying to use the index to find the offset value for a student which is entered by the user, I am having trouble using the strcmp() function to compare the value entered to those values held in the index.dat file.

Any help would be much appreciated here is the code so far.

void display_a_student()
{
        struct student aStudent;

        char studentNumSearch[11];
        int index=0;
        int found = false;

        fp = fopen("binary1.dat", "a+b");
        fp1 = fopen("index.dat", "a+b");

        printf("\n\nWhich student are you searching for?");
        scanf("%s", studentNumSearch);
        fflush(stdin);

    while(!found && index < 10)
    {
        if(strcmp(studentNumSearch,fp1[index].studentNum)==0)
        {
            found = true;
        }
        index++;
    }

    if (found)
    {
        fseek(fp, fp1[index].offset, SEEK_SET);
        fread(&aStudent,sizeof(struct student),1,fp);
        printf("\n\nThe student name is %s\n",aStudent.firstName);
    }
    else
    {
        printf("\n\nNo such student\n");

    }

    fclose( fp ); /* fclose closes file */
    fclose (fp1);
    getchar();

}

I am certain the line: if(strcmp(studentNumSearch,fp1[index].studentNum)==0) is where i am going wrong as i am unsure how to point to the file开发者_StackOverflow社区 while using the strcmp() function. - edited code for relevance.


strcmp is for string comparison. Use memcmp for binary comparison.

The main issue is your access to fp1[index]. This won't work as you access a FILE element never allocated. fp1 is not an array, but a FILE pointer.

You need to use fscanf or fread to read from the file and fseek to position correctly in the file based on index and size of each entry.


I dont think u should use strcmp, you have to use fread to copy into a structure and then use strcmp of what ever you want. If you have to use the way u did.. u have use memcmp instead of strcmp, but as Benoit said u need to know the length before u do a cmp.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜