I am working with fread()
in C. I am trying to read content of a binary file name pds_demo.bin but somehow my fread
function is not advancing. I checked the returned value of fread()
in gdb it is returning 0.
There are totally 3 files I am working with pds_functions.c, pds_test.c and the pds_demo.bin (contains the data to be read).
pds_test.c is calling a function named pds_search_by_key()
in pds_functions.c to check for a particular. This function checks the content of demo file and returns the status whether the record is present or not. I have included all the files below.
Any kind of help would be appreciated. Thanks.
pds_test.c:
void test_search() {
int status;
struct Contact c3;
int key;
key = 101;
status = pds_search_by_key(key, &c3);
if (status != PDS_SUCCESS) {
fprintf(stderr, "pds_search_by_key failed for key %d: errorcode %d\n", key, status);
} else {
printContact(&c3);
}
key = 102;
status = pds_search_by_key(key, &c3);
if (status != PDS_SUCCESS) {
fprintf(stderr, "pds_search_by_key failed for key %d: errorcode %d\n", key, status);
} else {
printContact(&c3);
}
key = 1020000;
status = pds_search_by_key(key, &c3);
if (status != PDS_SUCCESS) {
fprintf(stderr, "pds_search_by_key failed for key %d: errorcode %d\n", key, status);
} else {
printContact(&c3);
}
}
pds_functions.c:
int pds_search_by_key(int key, struct Contact *c) {
fseek(repo_fptr, 0L, 0);
if (pdsInfo.repo_status == 1) {
while (!feof(repo_fptr)) {
fread(c, sizeof(struct Contact), 1, repo_fptr);
if (c->contact_id == key) {
return PDS_SUCCESS;
}
}
return PDS_REC_NOT_FOUND;
}
return PDS_REPO_NOTOPEN;
}
pds_demo.bin:
101 Contact #1 Phone #1 Email #1 102 Contact #2 Phone #2 Email #2 102 Contact #2 Phone #2 Email #2
There is also one structure which define the structure Contact.
struct Contact {
int contact_id;
char cname[MAX_NAME_LEN];
char mphone[MAX_PHONE_LEN];
char email[MAX_EMAIL_LEN];
};
Also when I debug the program using gdb the content of *c is as follows:
(gdb) p *c
$1 = {contact_id = 540094513, cname = "Contact #1 Phone #1 Email #1 102
Contact #2 Phone ", mphone = "#2 Email #2",
email = " 102 Contact #2 Phone #2 Email #2 \377\377\177\000\000\t\t@\000\000\000\000\000\000\000"}