The following program creates a new dat file and stores random data. Then one of the values is searched from the file and printed.
The problem is data up to 13 items are searched and the program exits. As shown in following picture 100 inputs are stored and only 13 items are searched. What is the solution?
// database for storing random values in file and making search operation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int rollNo;
int regdNo;
int salary;
int status;
} record;
int main(void) {
int i, n;
record det;
int recordsize = sizeof(det); // size of record
FILE *fp1 = fopen("random.dat", "a+");
if (fp1 == NULL) {
printf("error in opening file : \n");
return 1;
}
printf("enter the no of data to be stored\n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
det.rollNo = rand();
det.regdNo = rand();
det.salary = rand();
det.status = (rand() % 10) + 1;
fwrite(&det, recordsize, 1, fp1);
}
printf("The last roll no of student stored in list: %d\n", det.rollNo);
int stat = 0, countNumber = 0;
record buffer;
int number;
printf("enter the roll number to be searched\n");
scanf("%d", &number);
fseek(fp1, 0, SEEK_SET); // move file position indicator to beginning of file
do {
countNumber++; // counts number of times the file is searched
fread(&buffer, recordsize, 1, fp1);
if (buffer.rollNo == number) {
stat = 1;
break;
}
} while (!feof(fp1));
printf("\n");
if (stat) {
printf("succesfully found at %d\n", countNumber);
printf(" roll number %d\n regd number %d\n salary %d\n status %d\n",
buffer.rollNo, buffer.regdNo, buffer.salary, buffer.status);
} else
printf("there is no such roll number %d in the list\nlength of list : %d\n",
number, countNumber);
fclose(fp1);
}
The output is: