Problem on reading a binary file using fread function - c

I am tasked to create an inventory program that stores data using structure and save the data into a binary file. The program should then be able to load the data i.e. the structure elements from the binary file. I am able to save the input data to a binary file using the fwrite function; however, I am having a problem in loading the file to the program using the fread function.
I already looked for similar problems but I can't find a similar case wherein the fread is used to pass the structure elements saved to the structure variable in the program.
This is the code for my structure
struct details {
char name[30];
double price;
int code;
int qty;
};
details item[SIZE];
Function in adding an item to the inventory
int AddItem(int n){
details inputitem;
printheader();
printf("Item Name: ");
scanf("%s", inputitem.name); //check %[^\n]
printf("\nItem Price: ");
scanf("%lf", &inputitem.price);
printf("\nItem Code: ");
scanf("%d", &inputitem.code);
printf("\nQuantity: ");
scanf("%d", &inputitem.qty);
printf("\nItem Added! The ID of the item is %d.\n", n+1);
item[n] = inputitem;
}
Function in displaying the inventory
int DisplayInventory(int n){
printheader();
printf("ID | NAME | CODE | QUANTITY | PRICE \n");
printf("------------------------------------------------------------\n");
for(int i=0; i<n; i++){
printf("%d %-18s %-10d %-10d %-10lf \n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price);
}
}
Function in saving to a binary file
int SaveFile(int n){
FILE *fp;
fp=fopen("C:\\Users\\Royce\\Documents\\CPEPROG2 Goden Final Project\\Inventory.txt","wb");
if(!fp) {
printf("Cannot open file.\n");
system("pause");
exit(1);
}
for(int i=0; i<n; i++){
fwrite(&item[i], sizeof(struct details), 1, fp);
}
fclose(fp);
printf("File is saved!\n");
}
Function in loading the binary file
int LoadFile(int n){
FILE *fp;
fp=fopen("C:\\Users\\Royce\\Documents\\CPEPROG2 Goden Final Project\\Inventory.txt","rb");
if(!fp) {
printf("Cannot open file.\n");
system("pause");
exit(1);
}
struct details inputitem;
int i = 0;
while(fread(&inputitem, sizeof(struct details),1, fp)){
item[i] = inputitem;
i++;
/* printf("%d %-18s %-10d %-10d %-10lf \n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price); */
}
fclose(fp);
printf("File is loaded!\n");
}
I expect the program to show in the DisplayInventory function the details of the structure saved in the binary file. However, nothing shows up at all.
When i try to print the structure in the LoadFile function (using the commented line), all variables show 0.
EDIT
Main Function
int main (){
int choice; //gets the choice of user from the menu
bool condition = 1; //loops the menu
//details item[50];
int count=0; //counts the number of items in the inventory
do{
printheader(); //prints the title of the program
printmenu(); //prints the menu (list of commands)
scanf("%d", &choice);
switch(choice){
case 1: system("cls");
AddItem(count);
count++;
system("PAUSE");
system("cls");
break;
case 2: system("cls");
//EditItem();
system("PAUSE");
system("cls");
break;
case 3: system("cls");
//DeleteItem();
system("PAUSE");
system("cls");
break;
case 4: system("cls");
//ViewItem();
system("PAUSE");
system("cls");
break;
case 5: system("cls");
DisplayInventory(count);
system("PAUSE");
system("cls");
break;
case 6: system("cls");
SaveFile(count);
system("PAUSE");
system("cls");
break;
case 7: system("cls");
LoadFile(count);
system("PAUSE");
system("cls");
break;
case 8: printf("\nThank you!");
exit(0);
break;
default: printf("\nInvalid Input!\n");
getch();
system("cls");
}
}while(condition = 1);
return 0;
}

The program never increments the 'count' variable, so when 'DisplayInventory' is called the value is always 0 and nothing is displayed :
return the i variable in 'LoadFile()' and assign it to the 'count' variable in the main() scope :
in LoadFile :
...
printf("File is loaded!\n");
return i;
}
in main :
...
case 7: system("cls");
count = LoadFile(count);
system("PAUSE");
system("cls");
Note that the 'n' argument in 'int LoadFile(int n)' is not used, you could remove it.

Related

Create a file and write struct with data member and the file created is empty

I create a program that prompts the user to choose an option, like below:
create a file and name the file.
add component in the file
display the item in the file
exit program
So my problem is the file is created and exists in my directory, but it is empty, so where did I miss something? plus can you check whether the 2 and 3 option program are OK?
Here my program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num, name;
start:
printf("\n1. Create a file.");
printf("\n2. Add a component to the list.");
printf("\n3. Display the current list of component.");
printf("\n4. Exit program.");
printf("\n\nChoose either these four menu = ");
scanf("%d", &num);
fflush(stdin);
switch (num) {
case 1:
printf("\n\nPlease enter file name: ");
scanf("%d", &name);
FILE *pf = NULL;
char username[250];
char userfile[255];
printf("username: ");
scanf("%s", username);
sprintf(userfile, "%s.txt", username);
fflush(stdin);
goto start;
break;
case 2:
pf = fopen(userfile, "w");
if (!pf) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
struct date {
int day;
int month;
int year;
};
struct details {
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
struct details item[50];
int n, i;
printf("Enter number of items:");
scanf("%d", &n);
fflush(stdin);
for (i = 0; i < n; i++) {
fflush(stdin);
printf("Item name: \n");
scanf("%s", item[i].name);
fflush(stdin);
printf("Item code: \n");
scanf("%d", &item[i].code);
fflush(stdin);
printf("Quantity: \n");
scanf("%d", &item[i].qty);
fflush(stdin);
printf("price: \n");
scanf("%d", &item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy): \n");
scanf("%d-%d-%d", &item[i].mfg.day,
&item[i].mfg.month, &item[i].mfg.year);
}
fclose(pf);
goto start;
break;
case 3:
pf = fopen(userfile, "r");
if (!userfile) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
{
printf(" ***** INVENTORY ***** \n");
printf("------------------------------------------------------------------\n");
printf("S.N.| NAME | CODE | QUANTITY | PRICE | MFG.DATE \n");
printf("-------------------------------------------------------- ---------\n");
for (i = 0; i < n; i++)
fprintf("%d %-15s %-d %-5d %-5d %d/%d/%d \n",
i + 1, item[i].name, item[i].code, item[i].qty,
item[i].price, item[i].mfg.day, item[i].mfg.month,
item[i].mfg.year);
printf("------------------------------------------------------------------\n");
}
fclose(pf);
goto start;
break;
case 4:
printf("Exit Program, Thank You, Sayonara");
break;
}
return 0;
}
There are multiple problems in your code:
the test if (!userfile) is incorrect: you should test if (!pf) instead
you open the file for reading, you should open it for writing with "w", or possibly for appending with "a".
you never write to the file. You should use fprintf(pf, ...) instead of printf.
the arrays userfile, item and variables i and n are local inside the switch statement: their contents go out of scope when you go to the start label outside de switch statement. Move all these definitions outside the switch statement.
fflush(stdin); has undefined behavior. You can consume (flush) the rest of the input line with: int c; while ((c = getchar()) != EOF && c != '\n') continue; You can define a function flush() that does it.

My basic trade program in C does not store any modifications when I close command prompt

#include<stdio.h>
int main() {
//After selling and buying i want it to modify this
struct music {
int srno;
char name[10];
int upperlimit;
int lowerlimit;
int avarn;
};
//Structure to maintain personal data
struct custormer {
int srno;
char name[5];
int upperlimit;
int lowerlimit;
int avarn;
};
FILE *f1;
int choice,amount,price;
int x,code,j=0;
struct music m1[] = {1,"Apple",100,98,10,2,"Valve",100,98,10,3,"Google",90,80,10,4,"Tesla",100,98,10};
struct music m2[10];
f1 = fopen("4.DAT","rb+");
if(f1==NULL)
{
printf("File does not exist!");
exit(0);
}
while(1)
{
printf("___________________________________\n");
printf("MENU\n");
printf("___________________________________\n");
printf("1) Stock Market\n");
printf("2) Buy\n");
printf("3) Personal Info\n");
printf("4) Sell\n");
printf("5) Exit\n");
printf("Enter choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("Stock Market\n");
printf("___________________________________\n");
for(x=0;x<4;x++)
{
printf("%d\t %s\t %d\t %d\t %d\n",m1[x].srno,m1[x].name,m1[x].upperlimit,m1[x].lowerlimit,m1[x].avarn);
fwrite(&m1,sizeof(m1),1,f1);
}
break;
}
case 2:
{
printf("Enter code of Stock:");
scanf("%d",&code);
printf("Enter number of stocks:");
scanf("%d",&amount);
printf("Enter price:");
scanf("%d",&price);
rewind(f1);
for(x=0;x<4;x++)
{
if(price>m1[x].lowerlimit&&price<m1[x].upperlimit)
{
if(m1[x].srno==code)
{
printf("Trasaction Is Succesful\n");
m1[x].avarn = m1[x].avarn-amount;
fwrite(&m1,sizeof(m1),1,f1);
m2[j].srno = j+1;
strcpy(m2[j].name,m1[x].name);
m2[j].avarn = amount;
j++;
}
}
}
break;
}
case 3:
{
for(x=0;x<j;x++)
{
printf("%d\t %s\t %d\n ",m2[x].srno,m2[x].name,m2[x].avarn);
fseek ( f1, sizeof(m1), SEEK_CUR ) ;
fwrite ( &m2, sizeof(m2), 1, f1 ) ;
}
break;
}
case 4:
{
printf("Enter code of stock to sell:");
scanf("%d", &code);
printf("Enter amount to sell:");
scanf("%d",&amount);
printf("Enter price to sell:");
scanf("%d",&price);
for(x=0;x<4;x++)
{
if(price>m1[x].lowerlimit&&price<m1[x].upperlimit)
{
if(m1[x].srno==code)
{
printf("Transaction is Sucessful\n");
m1[x].avarn = m1[x].avarn+amount;
fwrite(&m1,sizeof(m1),1,f1);
}
}
}
break;
}
case 5:
{
printf("Thanks!");
exit(0);
}
default:
{
printf("Invalid input!");
exit(0);
break;
}
}
}
fclose(f1);
return 0;
}
The program will execute and run but it will not store any data that I add when I buy or sell stocks, I'm still learning file operations, can someone correct this program or tell me how to do it? I feel like the fwrite() function is maybe not taking in the values I'm giving it The program will execute and run but it will not store any data that I add when I buy or sell stocks, I'm still learning file operations, can someone correct this program or tell me how to do it? I feel like the fwrite() function is maybe not taking in the values I'm giving it
You are using the wrong operator for testing equality.
if(f1=NULL)
This statement will assign NULL to f1, which will then evaluate to false.
You should use if (f1 == NULL) to test if it's NULL. Or just simply if (f1).
Something else strange that you are doing is opening the file twice, leaking the first handle. You should close it first, or open it only once.
Also, you should pay attention to the open mode. Your second call will actually destroy the file's contents. Read the documentation.

Using data inside a binary file in a conditional statement

It's my first time asking here, so I'm sorry in advance if my post is a bit messy. I'm a freshman and my finals is to make an atm program.
My program uses switch statements for the options: the first one asks the user for their info, (account number, account name, PIN, initial deposit), while the second one is for the actual transactions: Balance check, Deposit and Withdrawal. Before you could do any one of those options, of course I'll have to check if the info (in this case the account number and PIN) matches the ones in my file.
The file is in binary. My problem is that my code for reading the file works fine if i want to display the contents of my file (all the data entries that I populated the file with are shown), but when i want to use the contents of the file (searching inside the file for a match of the user inputted account number) it only reads the first line of the file, thus only the first data entry works, while the one's after that are not read.
My question is, what am i doing wrong in my code? its confusing because if I change my code to display the contents it shows everything, meaning it reads the whole file. but when i want to search the file using a conditional statement, only the first data entry gets read. Thank you very much for your time
tldr: can't use data in file for conditionals (verify the data inside the file, cuz my code doesn't read it whole apparently, except for the first entry)
but if i print the contents it reads it fully
my outputs
1.My data entries
data entries
2.Entering the Account no. of the 1st one (desired output)
desired output
3.Entering The account no. of the 2nd one (Problem part)
problem
my main code
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#include<process.h>
struct account
{
int no;
char name[100];
int pin;
float id;
};
main()
{
FILE *fptr;
fptr = fopen("accrec.dat","ab");
if (fptr == NULL)
{
printf("File does not exists \n");
return 0;
}
system("cls");
struct account accrec;
int i,tpin[4];
char step1,ch;
printf("\t\tWelcome to Banking System\n\t");
printf("\nA.Open an Account\n");
printf("\nB.Bank Transaction\n");
printf("\nC.exit\n");
scanf("%c",&step1);
switch (step1)
{
case 'A':
printf("Open a New Account\n");
printf("\nEnter the following information\n");
printf(" \n5-digit Account number:");
scanf("%d",&accrec.no);
getchar();
printf("\nAccount Name:");
scanf("%[^\n]s",&accrec.name);
printf("\n4-digit Account PIN:");
/*for(i=0;i<4;i++)
{
ch = getch();
tpin[4] = ch;
ch = '*' ;
printf("%c",ch);
}mask works but does not allow PIN saving */
scanf("%d",&accrec.pin);
printf("\nInitial deposit:");
scanf("%f",&accrec.id);
fwrite(&accrec,sizeof(struct account),1,fptr);
fclose(fptr);
break;
case 'B':
{
fptr = fopen("accrec.dat","rb");
int choice;
int accno = 0;
printf("Enter Your Account no.");
scanf("%d",&accno);
while (fread(&accrec,sizeof(account),1,fptr)!=NULL)
{
if(accno == accrec.no)
{
printf("\tWelcome to PUPQC Banking System\n");
printf("1.Balance Inquiry\n");
printf("2.Deposit\n");
printf("3.Withdrawal\n");
printf("4.quit\n");
scanf("%d",&choice);
}
else
{
printf("account doesn't exist\n");
exit(1);
}
fclose(fptr);
switch (choice)
{
case 1:
printf("BALANCE INQUIRY\n");
printf("Current Balance:");
fptr = fopen("accrec.dat","rb");
if (fptr == NULL)
{
printf("File Cant be read");
exit(1);
}
printf("Account No: %d\n",accrec.no);
while(fread(&accrec,sizeof(struct account),1,fptr)!=NULL);
{
printf("Initial Deposit is %0.2f\n",accrec.id);
}
printf("%d\n",&accrec.id);
break;
case 2:
float dv;
printf("DEPOSIT\n");
printf("Current Balance:");
fptr = fopen("accrec.dat","rb");
if (fptr == NULL)
{
printf("File Cant be read");
exit(1);
}
while(fread(&accrec,sizeof(struct account),1,fptr)!=NULL);
{
printf("%0.2f\n",accrec.id);
}
printf("Enter amount to deposit:\n");
printf("Deposit Value:");
scanf("%0.2f",&dv);
accrec.id = accrec.id + dv;
fwrite(&accrec,sizeof(struct account),1,fptr);
fclose(fptr);
break;
case 3:
float wv;
printf("WITHDRAWAL\n");
printf("Current Balance:");
fptr = fopen("accrec.dat","rb+");
if (fptr == NULL)
{
printf("File Cant be read");
exit(1);
}
while(fread(&accrec,sizeof(struct account),1,fptr)!=NULL);
{
printf("%0.2f\n",accrec.id);
}
printf("Enter amount to withdraw:\n");
printf("Withdrawal Value:");
scanf("%0.2f",wv);
accrec.id = accrec.id - wv;
fwrite(&accrec,sizeof(struct account),1,fptr);
fclose(fptr);
break;
case 4:
printf("thank you for your patronage \n");
return 0;
break;
default:
printf("error 404");
break;
}
}
}
break;
case 'C':
printf("Thank you! Have a good day");
return 0;
break;
case 'D':
fptr = fopen("accrec.dat","rb");
if (fptr == NULL)
{
printf("File Cant be read");
exit(1);
}
printf("Data From file\n");
while(fread(&accrec,sizeof(struct account),1,fptr)!=NULL)
printf("\n acc.no is %d\n acc.name is %s\n PIN %d\n Initial Deposit is %0.2f\n ",accrec.no,accrec.name,accrec.pin,accrec.id);
fclose(fptr);
getch();
break;
default:
printf("invalid input! please select form the options given\n");
}
}
my structure
struct account
{
int no;
char name[100];
int pin;
float id;
};
code for finding a match of account number in my file
(the part i'm having trouble with)
fptr = fopen("accrec.dat","rb");
int choice;
int accno = 0;
printf("Enter Your Account no.");
scanf("%d",&accno);
while (fread(&accrec,sizeof(account),1,fptr)!=NULL)
{
if (accno == accrec.no)
{
printf("\tWelcome to Banking System\n");
printf("1.Balance Inquiry\n");
printf("2.Deposit\n");
printf("3.Withdrawal\n");
printf("4.quit\n");
scanf("%d",&choice);
}
else
{
printf("account doesn't exist\n");
exit(1);
}
}
fclose(fptr);
The expected output is that my conditional statement works properly and reads my whole file for matches.
try to change the exit(1) to continue;, the exit(1) will make your program quit the while loop and exit the program immediately whenever accno != accrec.no.
in fact, you don't need the else statement inside the while loop, you should put it outside the while loop. for example:
scanf("%d",&accno);
boolean found = false;
while (fread(&accrec,sizeof(account),1,fptr)!=NULL)
{
if (accno == accrec.no)
{
found = true;
scanf("%d",&acpin);*/
printf("\tWelcome to Banking System\n");
printf("1.Balance Inquiry\n");
printf("2.Deposit\n");
printf("3.Withdrawal\n");
printf("4.quit\n");
scanf("%d",&choice);
}
}
if (!found) {
printf("account doesn't exist\n");
}
fclose(fptr);

Menu not working properly

#include <stdio.h>
#include <stdlib.h> //for the clear screen function
#include <string.h>
struct customer
{
int custID;
char custName[50];
char custAddress[100];
};
typedef struct customer c;
void load_menu(void);
void customers_menu(void);
void createNew(void); //initialize your file
void add_Customer(c c1[30]); //add a new record to the file
FILE *fp;
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
do
{
printf("Customer Orders Main Menu. \n\n");
printf("Please enter your choice: \n");
printf("1. Customer's Menu \n");
printf("2. Orders Menu\n");
printf("3. Product Stock Menu\n");
printf("4. Exit\n");
printf("\n");
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: system ("cls");
customers_menu();
printf("\n");
break;
case 2: system ("cls");
orders_menu();
printf("\n");
break;
case 3: system ("cls");
stock_menu();
printf("\n");
break;
case 4: printf("Quitting program!\n");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
}
void createNew(void)
{
FILE *fp;
fp=fopen("Customer.dat", "w");
if (fp==NULL)
printf("File creation failed! \n");
else
{
printf("File created! \n");
fclose(fp);
}
}
void add_Customer (c c1[30])
{
int i, n , cc=0;
FILE *fp;
fp=fopen("Customer.dat", "a");
system("cls");
if(fp==NULL)
{
printf("File Creation Failed!");
}
system("cls");
printf("Enter the number of Customers: ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("Customer's ID (numbers only) : ");
scanf("%d", &c1[i].custID);
printf("Customer's Name : ");
gets(c1[i].custName);
printf("Customer's Address : ");
gets(c1[i].custAddress);
fwrite(&c1[i], sizeof(c), 1, fp);
}cc++;
fclose(fp);
}
void recordCount(c c1[30], int *count)
{
add_Customer(c1);
count=0;
count++;
}
void customers_menu(void)
{
int choice;
c c1[30];
int i;
do
{
printf("\n");
printf("Customers Menu \n\n");
printf("Please enter your choice: \n");
printf("1. Add Customer \n");
printf("2.\n");
printf("3.\n");
printf("4. Go back to Main Menu \n");
recordCount (c1, &i);
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: add_Customer(c1);
createNew();
printf("\n");
break;
case 2:
printf("\n");
break;
case 3:
printf("\n");
break;
case 4: printf("Going back to Main Menu\n");
system ("cls");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
I have a problem since when I enter the Customers Menu it is staring to execute case 1 immediately (which still doesn't work properly). Can someone help me fix this error please because I tried everything I know and it is still in vain
I think your issue is that in customers_menu() you output the menu, but do not read the selection, instead you call recordCount() which directly calls addCustomer().
After addCustomer() we return the customers_menu() which then calls scanf() for the long gone menu.
A few other notes:
gets() is not good, I suggest you use scanf() (with %s) instead.
Doing a printf() then clearing the screen is a bit pointless.
Error messages should really go to stderr (fprintf(stderr,...)) rather than stdout (printf(...))
You code is a missing trailing }.
cc is added to, but not used.
This problem coming from if (scanf("%d",&choice)==1) because scanf will not return choice. If you enter valid answer (like number), then it returns 1 and switch case work with 1. I think that's the problem.
If you enter char instead of integer, scanf will return 0.

C prog: Write to and from binary files not working?

I've got a question concerning C programming.It is concerning binary files.In my code I(at least imagined that I) made it read and write from a binary file,but it won't do that for some reason.I've tried changing some things but I just don't see the error anywhere.And it is just this minimal detail which is giving me a hard time,it is all that is left to make in this code before it is done and then I'm done with the program altogether,so it gets on my nerves a bit more than it would usually.Please point out what it is I haven't done and what i should do to make it read from and write to binary files properly:
#define MAX 4
//========================-STRUCTURE-=====================================================================
struct person{
char name[30];
char mail[30];
char tele[30];
};
struct person p[MAX];
//========================-MAIN FUNCT-===============================================================
int main()
{
bool continue=true,exists=false;
int answer,i;
char filnme[20];
FILE *fil;
printf("Would you like to open an already existing file?[y/n]: ");
scanf("%d",&answer);
if(answer=='y'||answer=='Y')
{
finns=true;
}
else finns=false;
getchar();
printf("\n\nType the name of the file you will use: ");
scanf("%s",filnme);
if(exists)
{
fil = fopen(filnme,"rb");
for(i=0;i<MAX;i++)
{
while(feof(fil)==0)
{
fread(&p, MAX, 1, fil);
printf("%s %s %s\n",p.name,p.mail,p.tele);
}
}
fclose(fil);
}
else fil = fopen(filnme,"wb");
do
{
system("cls");
int choice;
printf("What would you like to do?");
printf("\n_______________\n");
printf("1. Add another person to the list\n");
printf("2. Print the entire list\n");
printf("3. Remove information from the list\n");
printf("4. Sort\n");
printf("5. Change information\n");
printf("6. Search\n");
printf("7. Exit\n");
printf("\nChoice: ");
scanf("%d",&choice);
printf("\n");
system("cls");
switch(choice)
{
case 1:
addtolist();
getch();
break;
case 2:
write();
getch();
break;
case 3:
remove();
getch();
break;
case 4:
sort();
getch();
break;
case 5:
change();
getch();
break;
case 6:
search();
getch();
break;
case 7:
continue=false;
break;
default:
printf("Not a valid choice!");
getch();
break;
}
}while(continue);
for(i=1;i<=MAX;i++)
{
fwrite(&p, MAX, 1, fil);
}
fclose(fil);
system("cls");
}
Nevermind the declaration of functions or such,I've got that covered,just the binary file handling I put into the main.
Thanks in advance!
You are not using fread and fwrite correctly.
fread(&p, MAX, 1, fil);
should be:
fread(&p[i], sizeof(person), 1, fil);
Similarly for the fwrite call.
An alternative to calling fread and fwrite in a loop is to read/write the entire array in one go, like so:
fread(&p, sizeof(person), MAX, fil);
continue is a reserved keyword in C/C++ - don't use that as a boolean variable name.
finns is not declared (assumed to be bool)
You aren't checking the return value of fopen. How do you know if the file was successfully opened?
Your while loop on fread does't look anywhere near right.
This looks much better
int records_read = 0;
size_t count;
count = 0;
for (i = 0; i < MAX; i++)
{
count = fread(&p[i], sizeof(p[i]), 1, fil);
if (count == 0)
{
break;
}
records_read++;
}
Same for your write loop (note that I adjusted the starting value of "i")
for(i=0;i<MAX;i++)
{
fwrite(&p[i], sizeof(p[i]), 1, fil);
}
Apart from other things, scanf("%d", &answer) attempts to read a number, not a y/n character.

Resources