Reputation: 623
I'm trying to update some info in my binary file, but I'm facing a problem while trying to go backward, to the beginning of the line.
void updateSalary(char* filename)
{
int i = 0;
employee temp;
char c;
float increase;
FILE *fup = fopen(filename, "rb+");
if (fup == NULL)
{
printf("Unable to read the file\n");
return;
}
fread(&temp, sizeof(employee), 1, fup);
while (!feof(fup))
{
printf("How big is the increase to %s's salary?\n", temp.name);
scanf("%f", &increase);
temp.salary += increase;
fseek(fup, (i * sizeof(employee)), SEEK_SET);
fwrite(&temp, sizeof(employee), 1, fup);
fread(&temp, sizeof(employee), 1, fup);
i++;
}
fclose(fup);
}
The problem is, for instance, if I choose to update 2 employees, for some reason, the while loop doesn't stop at the 2nd employee and the function keep going..
Thanks in advance.
Edit: it seems that the fwrite(); function didn't advance (by position meaning) til the next line, so there is the fixed code:
void updateSalary(char* filename, float threshold)
{
int i = 0;
employee temp;
char c;
float increase;
FILE *fup = fopen(filename, "r+b");
if (fup == NULL)
{
printf("Unable to read the file\n");
return;
}
//fread(&temp, sizeof(employee), 1, fup);
while (fread(&temp, sizeof(employee), 1, fup))
{
printf("How big is the increase to %s's salary?\n", temp.name);
rewind(stdin);
scanf("%f", &increase);
temp.salary += increase;
fseek(fup, (i * sizeof(employee)), SEEK_SET);
fwrite(&temp, sizeof(employee), 1, fup);
**fseek(fup, ((i+1) * sizeof(employee)), SEEK_SET);**
i++;
}
fclose(fup);
}
Upvotes: 1
Views: 676
Reputation: 92231
You should check the fine print in the fopen
documentation:
In update mode ('+'), both input and output may be performed, but output cannot be followed by input without an intervening call to fflush, fseek, fsetpos or rewind, and input cannot be followed by output without an intervening call to fseek, fsetpos or rewind, unless the input operation encountered end of file.
Reading and writing might be buffered, but still share a single file position. Switching modes without alerting the runtime (using fseek
) could mess up the buffering.
So the lines
fseek(fup, (i * sizeof(employee)), SEEK_SET);
fwrite(&temp, sizeof(employee), 1, fup);
fread(&temp, sizeof(employee), 1, fup);
need one more fseek
between write and read.
Upvotes: 2