I’ve created a binary file with three persons (Code-Name-Sex) when I write the data into the file and then I read them, it work perfectly so..
I want that the next function read all the information of the X person have (if it exist).
Syntax:
#include <stdio.h>
struct alu{
int cod;
char name[30]; //alu[0]="juan" alu[1]="pedro" alu[2]="leo"
int sex;
};
int FSearch(char path[],char X[]) {
char Name[30];
FILE *arc;
arc=fopen(path,"rb");
fseek(arc,sizeof(int),SEEK_SET);
while (fread(Name,sizeof(char[30]),1,arc)) {
/*Here is when the errors happen..
The next sentence tell me that A.name don't have
the name from the second time*/
printf("%s and %s.",X,Name);
if (strcmp(Name,X)==0) return 1;
fseek(arc,2*sizeof(int),SEEK_CUR);
}
fclose(arc);
return 0
}
int main(int argc, char **argv)
{
char path[]="file.bin";
printf("\n%d",FSearch(path,"pedro"));
return 0;
}
The output is the following:
pedro and juan.pedro and .pedro and .
0
That means that is found the first name (‘juan’) but the second and third isn’t (pedro and leo).
What is wrong?
Here’s how it was:
Here’s how it should be:
The problem was the 2nd argument, the Number of bytes to offset from origin, passed to
fseek()call, within the while loop. It was counting two INTs but not the two CHARs (before reaching to the second string). You can see thesizeof(char[30])after thefread()call, it shows 32 bytes, but 30 bytes are allocated to the string.Why have to move two more bytes? Because any string have in its end, reserved bytes (for indicating the beginning and end of the string). e.g.:
If you save this into a binary file, this file will have a size of 12 bytes.