如何在不将文件复制到另一个文件的情况下更改文件中的整数

How to change an integer inside a file without coping the file to another

我正在为学校制作一个程序,我必须创建一个用于考试的函数和另一个用于参加考试的函数。 我做了创建考试的部分。现在我正在努力做好准备参加考试。我在这部分遇到的问题是将考试的分数存储在学生数据中。我正在尝试使用“fseek()”,但我做对了。 这是我尝试过的:

void take_exam()
{
    int id_temp;
    int n,sum=0;
    char answer[20];
    printf("Choose the subject:\n");
    printf("1.Math\n");
    printf("2.English\n");
    printf("3.Physics\n");
    
    scanf("%d",&n);
    
    FILE *finside;
    finside=fopen(name_student,"rb+"); //open the student file. The students are registered in ab+ mode
    if(finside==NULL)
    {
        printf("Error in file");
        return;
    }
    
    switch (n)//used switch case for the different subjects
    {
        case 1:
        FILE *f;
        f=fopen(name_math,"rb");//opened the math file, where i have stored the question and answers
        if(f==NULL)
        {
         printf("Error in file");
            return; 
        }
        while(fread(&math,sizeof(struct subject),1,f))
{
        system("cls");
        printf("Enter your ID");
        scanf("%d",&id_temp);
        printf("====Start the exam=====\n");

    for(int i=1;i<=6;i++)// I have done each exam with 6 questions
    {
        fflush(stdin);
        printf("\nQuestion number %d\n",i);
        printf("%s\n",math.q[i].question);
        printf("%s\n",math.q[i].ans1);
        printf("%s\n",math.q[i].ans2);
        printf("%s\n",math.q[i].ans3);
        printf("%s\n",math.q[i].ans4);
    
        printf("Give your answer:");
        scanf("%[^\n]%*c",answer);

        // The part of points calculate fine
        if(strcmp(math.q[i].answer,answer)==0)
        {
            sum++;
        }
        else if(strcmp(math.q[i].ans4,answer)==0)
        {
            sum=+0;
        }
        else if((strcmp(math.q[i].answer,answer)!=0) && (strcmp(math.q[i].ans4,answer)!=0))
        {
            sum--;
        }
        
    math.q[i].points=sum;
    }
    printf("The exam is over!");}
        printf("You got %d points",sum);
    while(fread(&s[nr_student],sizeof(struct stud),1,finside))
        {
        fseek(finside,sizeof(struct stud),SEEK_SET);//The points are stored in this part but that student 
        if(s[nr_student].ID==id_temp)               // is repeated again. One with the primary points
        {                                           // and the other one with the points he's got.
            s[nr_student].points+=sum;
        }
        fwrite(&s[nr_student],sizeof(struct stud),1,finside);
    }
    fclose(finside);
    fclose(f);
    break;
case 2:
*** //and so on for the other subjects

我得到的输出: 编号:1 Name:John Points:0

编号:1 Name:John Points:6

编号:2 Name:Bill Points:0

提前致谢!

只有文件中的数字占用的字节数完全相同时,您才可以替换文件中的数字。但如果是这样的话,那么你的策略可能是:

  1. ftell当前位置

  2. 读取下一条记录

  3. 将其与您想要的记录进行比较。

  4. 如果是正确的,那么fseek到你从ftell

    得到的位置
  5. 写记录。