Hello,
I am struggling with my code. I have a structure in a binary file and I need to make a function that searches a structure FIRM by a number and then proceeds to edit its previously typed profit.
This is the code in the main function:
Code:
case 4: {
fflush(stdin);
printf("\nUpdate profit for firm with ID number:\n");
gets(searchM);
printf("\nNew profit:\n");
scanf("%d", &newprofit);
if (updateprofit(binary, filename, searchM, newprofit))
printf("Update done!\n");
else
printf("Not updated!\n");
system("pause");
break;
}
This is the header:
Code:
#include <stdio.h>#include <stdlib.h>
#include <malloc.h>
#include <string.h>
struct firm
{
char idn[13];
char name[40];
char date[10];
int profit;
};
typedef struct firm FIRM;
FILE *writeFile(char *fname);
void enter(FIRM **ps);
int readFile(FILE *fp, char *fname);
void display(FIRM *ps);
FILE *addInfo(char *fname);
int updateprofit(FILE *fp, char *fname, char *searchM, int newprofit);
And this is the function itself that gives and error and breaks the whole program.
Code:
int updateprofit(FILE *fp, char *fname, char *searchM, int newprofit){
FIRM s;
fp = fopen(fname, "r+b");
if (!fp)
return 0;
while (fread(&s, sizeof(FIRM), 1, fp) == 1)
{
if (strcmp(s.profit, searchM) == 0)
{
s.profit = newprofit;
fseek(fp, ftell(fp) - sizeof(FIRM), SEEK_SET);
fwrite(&s, sizeof(FIRM), 1, fp);
fclose(fp);
return 1;
}
}
fclose(fp);
return (0);
}
Thanks in advance!