【问题标题】:How to acess specific parts of files and use it in C programming?如何访问文件的特定部分并在 C 编程中使用它?
【发布时间】:2017-02-11 19:31:15
【问题描述】:

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

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

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

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

代码应该是怎样的?

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

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;

}

【问题讨论】:

  • 您使用的文件是一个结构良好的文本文件。阅读 fscanf 并使用它。
  • 不清楚你在问什么。此外,尚不清楚数据是什么样的。这看起来像家庭作业,这很好,但您需要更清楚地了解问题,以及您已经采取了哪些措施来解决它。
  • 对于文本文件,通常不可能找到数据的特定位置,因为文本文件中的元素通常是可变宽度。对于文本文件,通常必须读取整个文件,解析每条记录,直到找到所需的记录。
  • 这不是作业,我正在努力学习这些东西,并尝试从基础开始,以获得更强大的知识,尝试将代码放在这里。

标签: c fseek ftell


【解决方案1】:

我对您的问题有点困惑,但假设只有一个文件(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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多