-4

我正在学习如何用 C 语言编程,但我一直很难使用文件。

例如,我该怎么做,有两个文件。上面有名字和等级,从 1 到 10 名学生。喜欢:

John 10       John 5
Alex  6       Alex 9
Mary  8       Mary 6

如何从给定的学生那里访问特定的数字并添加数字,例如,我必须使用 fseek 、 SEEK_END 还是应该使用 ftell?并取所有的中位数?

代码应该如何?

编辑1:我尝试了什么(对不起葡萄牙语中的变量,我添加了一些评论):

enter code here


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{

char nome[30];
float media;
char situacao;

}informa;
// function to create files \/ 
int cria_arquivo(){
    informa A;
    char nome[30];
    float n1, n2;
    `FILE *arq1, *arq2, *arq3, *arq4;  //pointers to archives  students, grades,` and anothe file to print on

    arq1 = fopen("alunos.txt","r"); // students and grades
    arq2 = fopen("notas1.txt","r");
    arq3 = fopen("notas2.txt","r");
    arq4 = fopen("turma.dat", "wb");


   if((arq1 == NULL) || (arq2 == NULL) || (arq3 == NULL) || (arq4 == NULL)){
       printf("FATAL ERROR - NAO E POSSIVEL ABRIR ARQUIVOS");  //cant open the files
       exit(1);
    }

    while(1){
        //printf("ola");
        fscanf(arq1, "%s", nome);
        printf("%s\n", nome);



        if (feof(arq1)) {
            break;
        } 
        //printf("Funciona");

        fscanf(arq2, "%f", &n1);
        fscanf(arq3, "%f", &n2);


        strcpy(A.nome, nome);

        A.media = (n1+n2)/2;
        printf("%f\n", A.media);

        if(A.media < 5){
            A.situacao = 'F';
        }
        else{
        A.situacao = 'A';
        }

        fwrite(&A, sizeof(informa), 1, arq4);
    }
    fclose(arq1); fclose(arq2); fclose(arq3); fclose(arq4);
    return 0;
}

int main(){
    cria_arquivo();

    return 0;

}
4

1 回答 1

0

我对你的问题有点困惑,但假设只有一个文件(arq,aluno.txt)并且每一行都有一个名称和一个等级,例如:

   Lukas 10
   Matthias 8
   Sven 5
   Fernando 10

你想知道费尔南多的成绩,你可以做这样的事情:

   #include <stdio.h>
   #include <stdlib.h>
   #include <string.h>

   int main () {
      FILE *arq;
      arq = fopen ("aluno.txt", "rt");
      if (arq == NULL) {
         printf ("ERRO 404\n");
      }
      char name[50];
      int grade;
      while (fscanf (arq, "%s %d\n", &name, &grade) != EOF) {
          if(name = "Fernando"){
             //do what you want
             if(grade < 6){
                printf("Not good Fernando");
             }
          }
      }
   }

这种方法的好处是它会逐行运行并获取每行的名称和等级,直到它结束。因为 fscanf() 函数所做的是获取每一行的信息,然后移动到下一行,并在文件结束时返回 EOF。

于 2017-02-11T20:47:08.687 回答