There are couple of problems in your code:
You can't read struct fields one by one because there may be (an usually there is) padding added between struct fields. This means that if you have two fields in your struct -
char
(say, 1 byte large) an int, say4 byte large
, it's very likely that your struct will be 8 bytes large with 3 "empty" bytes between the char and an int. The padding is added because of alignment issues which are out of scope of this post. In order to fix this, you should read whole struct at once, just like you write it at once. Note, however, that since padding may be different on different architectures/C implementations, in this case you won't be able to freely move your files from machine to machine and expect your program to work. The other option, more portable, is to write the struct field by field. But also then, you have to consider what happens if you try exchanging you file with two machines, one with 4 byte int and one with 8 byte (quite unusual but possible). Yeah, C is actually hard to get it right.Your
key
value validation is wrong.key
should be allowed to be equal 0 since this is where first record will be stored. It should never be larger than(filesize/sizeof(struct pedia))-1
, though.Last argument of
lseek
should be one ofSEEK_SET
,SEEK_END
, orSEEK_CUR
, not0
as you have no guarantee that other C implementation will use the same number to representSEEK_SET
. The truth is, we can't really know what 0 means in case of your C implementation an since you don't check return value of the call, we can't even know if0
is valid value there.
Not to mention lack of error handling.. and that one actually comes in handy when your code is misbehaving.