I have a .txt file following the syntax:
studentName1 grade1
studentName2 grade2
.
.
.
I want to develop the C function int changeGrade(String name, int old_grade, int new_grade, String fileName)
That changes the grade of the specified Student with the new one.
#include <stdio.h>
#include <string.h>
typedef char String[30];
void changeGrade(String name, int old_grade, int new_grade, String fileName) {
long pos;
String temp;
int grade;
int test = 0;
if ((old_grade <= 10) && (old_grade >= 0)) {
FILE * fp = fopen(fileName, "r+");
while ((!test) && (!feof(fp))) {
pos = ftell(fp);
fscanf(fp, "%s %d\n", temp, & grade);
if (strcmp(name, temp) == 0 && grade == old_grade) {
fseek(fp, pos, SEEK_SET);
fprintf(fp, "%s %d", name, new_grade);
test = 1;
}
}
fclose(fp);
} else printf("Error,you must specify the grade");
}
int main(int argc,
const char * argv[]) {
changeGrade("Carl", 7, 6, "students.txt");
}
The code works, but if i have something like
changeGrade("Carl",10,7,"students.txt")
I get
Carl 70
Why?