Hello i have a structure in binary file and i want to make a search option by surname for example. I want to ask can somebody could post examples how to search by surname or something like this.
Hello i have a structure in binary file and i want to make a search option by surname for example. I want to ask can somebody could post examples how to search by surname or something like this.
How are the structs stored in the file? Are they all of equal size? Is the string part of the struct or only a pointer, if so, where are the strings? One approach for storing the structs is, one record per line, then you can use fgets/sscanf for example.
This is structure
This is how i store dataCode:struct student_list { int number; char student_code[20]; char surname[50]; char name[50]; double sholarship; };
And this is how i tried to searchCode:case 1: { if ( ( fp = fopen( "list.dat", "rb+" ) ) == NULL ) { printf("File does not exist. \n"); } else { printf("Enter student number "); scanf( "%d", &student.number ); printf("Enter student code, surname, name and scholarship \n"); fscanf(stdin, "%s%s%s%lf", student.student_code, student.surname, student.name, &student.scholarship); fseek( fp, ( student.number - 1 ) * sizeof( struct student_list ), SEEK_SET ); fwrite( &student, sizeof( struct student_list ), 1, fp ); } fclose( fp ); break; }
Code:case 2: { printf("Enter surname \n"); scanf("%s",sur); while ( !feof( fp ) ) { fread( &student, sizeof( struct student_list ), 1, fp ); if ( student.surname == sur ) { printf( "%-10d%-10s%-16s%-11s%10.2f\n",student.number, student.student_code, student.surname, student.name, student.scholarship ); } system("pause"); }
That may or may not work, depending on if the struct is padded or not. You can't really make any assumptions about it, it can differ among compilers and so on.
But, does it work? What size does sizeof( struct student_list ) return? Does it match the sum of the member sizes?
Besides that, you can search the entire file by wrapping fread in a while loop and overwrite student in each iteration.
That is does not work it returns nothing when i try to search.
In C you can't compare strings directly to each other, so this will never work:
You need to include the header file string.h in your program, and then do something like this:Code:if ( student.surname == sur )
The return from strcmp will either be a negative number (indicating student surname was larger than "sur"), a zero (indicating they are the same), or a positive number (indicating that student.surname was smaller than "sur").Code:if ((strcmp(student.surname,"sur"))==0)
So it's like a teeter-totter, with the pivot right between the two strings. If the left side is larger (heavier), the left side of the teeter-totter goes down, and the negative numbers result. If the right side is larger (heavier), the right side of the teeter-totter goes down, but now you're on the positive side of the the pivot point, so the result is a positive number.