#include <stdio.h>

#include <stdlib.h>



struct aluno{

      int matricula;

      char nome[51];

      float mensalidade;

};

typedef struct aluno Aluno;



Aluno Entrada_dados(){

      Aluno alu;

      printf("Matricula: ");

      scanf("%d", &alu.matricula);

      printf("Nome: ");

      scanf("%s", alu.nome);

      printf("Mensalidade: ");

      scanf("%f", &alu.mensalidade);

      return alu;

}



int Aluno_Inserir(FILE* fp,Aluno alu){

     Aluno aux;

     fseek(fp,-sizeof(Aluno),SEEK_END);

     while(fread(&aux,sizeof(Aluno),1,fp)){

        if (aux.matricula > alu.matricula){

                    fseek(fp, 0, SEEK_CUR);
fwrite(&aux,sizeof(Aluno),1,fp);

                  fseek(fp,-(sizeof(Aluno)*2),SEEK_CUR);

                  if(ftell(fp) == 0) break;

                  fseek(fp,-(sizeof(Aluno)),SEEK_CUR);

                        }

                        else break;

                        }

    fseek(fp, 0, SEEK_CUR);

    fwrite(&alu, sizeof(Aluno), 1, fp);

}



int main(){

    FILE* fp;

    fp = fopen("Arquivo.txt", "rb+");

    if(fp == NULL)

     fp = fopen("Arquivo.txt", "wb+");

    Aluno alu;

    alu = Entrada_dados();

    Aluno_Inserir(fp, alu);

}

Tutorial de uso de arquivo em linguagem c

  • 1.
    #include <stdio.h> #include <stdlib.h> structaluno{ int matricula; char nome[51]; float mensalidade; }; typedef struct aluno Aluno; Aluno Entrada_dados(){ Aluno alu; printf("Matricula: "); scanf("%d", &alu.matricula); printf("Nome: "); scanf("%s", alu.nome); printf("Mensalidade: "); scanf("%f", &alu.mensalidade); return alu; } int Aluno_Inserir(FILE* fp,Aluno alu){ Aluno aux; fseek(fp,-sizeof(Aluno),SEEK_END); while(fread(&aux,sizeof(Aluno),1,fp)){ if (aux.matricula > alu.matricula){ fseek(fp, 0, SEEK_CUR);
  • 2.
    fwrite(&aux,sizeof(Aluno),1,fp); fseek(fp,-(sizeof(Aluno)*2),SEEK_CUR); if(ftell(fp) == 0) break; fseek(fp,-(sizeof(Aluno)),SEEK_CUR); } else break; } fseek(fp, 0, SEEK_CUR); fwrite(&alu, sizeof(Aluno), 1, fp); } int main(){ FILE* fp; fp = fopen("Arquivo.txt", "rb+"); if(fp == NULL) fp = fopen("Arquivo.txt", "wb+"); Aluno alu; alu = Entrada_dados(); Aluno_Inserir(fp, alu); }