I was trying to create a function that receives a file, reads a line, and update some of the data.
so basically, I want to:
- Read the line and insert the data into local variables
- Move backward to the beginning of the salary item (in the file).
- Overwrite the new updated salary.
To bo me specific, the file includes employee's data (code, name, and salary) and the function needs to update the salary of each employee by any given addition.
example: 123, Joe, 1200
void updateSalary(char* filename)
{
employee temp;
char c;
float increase;
FILE *fup = fopen(filename, "r+");
while ((c=fgetc(fup)) != EOF)
{
fscanf(fup, "%*d%s%f", &temp.name, &temp.salary);
printf("How big is the increase to %s's salary?\n", temp.name);
scanf("%f", &increase);
while ((c=fgetc(fup)) != ' ')
fseek(fup, -1, SEEK_CUR);
fprintf(fup, "%f", temp.salary + increase);
fseek(fup, 1, SEEK_CUR);
}
fclose(fup);
}
How I thought to overwrite the new salary: I used a while loop to look for the backspace that appeared before the salary data while moving backward every byte and look for it. Not working correctly. second, after the print of the new data, the file position is set for the next char ('\n'
) and I would like to skip this one, so I used fseek with 1 byte. didn't work either.
Thanks!