Any idea why the following code isn’t working?
My struct:
struct Records
{
int Number;
char Name[20];
float Salary;
};
Code in main:
FILE * binaryfile;
binaryfile = fopen("binaryfile.dat","r+b");
struct Records MyRecords;
printf("Name: \n");
gets(MyRecords.Name);
printf("Yearly Salary: \n");
scanf("%f%*c",&MyRecords.Salary);
fseek(binaryfile,2L*sizeof(struct Records),SEEK_SET);
fread(&MyRecords.Number, sizeof(MyRecords.Number), 1, binaryfile);
fwrite(&MyRecords.Name, sizeof(MyRecords.Name), 1, binaryfile);
fwrite(&MyRecords.Salary, sizeof(MyRecords.Salary), 1, binaryfile);
I missed the lesson for binary so my understanding of this is very shaky, but this is what i’m trying to do:
With fseek, I’m going to the beginning of the 3rd record, which is “3,Random Name,50.00”.
Then I’m reading the 3 into MyRecords.Number (i’ve tested up to this point). Then when the pointer is on name, I’m attempting to overwrite it and the salary with new ones.
Yet somehow it doesn’t work. I’ve tried changing the file Opening to stuff like ab+, wb+, rb+, rb, with no success.
IMHO, you always should use a complete structure in your code: read it (i.e. fread(&MyRecords, sizeof(MyRecord)…) ), change the elements, fseek again at the same place and fwrite the whole structure. The way you are doing, you may experience any sort of problems with data alignment.