Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Menu(FILE *f);
typedef struct
{
int numTeste;
float nota;
char descricao[50];
}Aluno;
void Listar(FILE *f)
{
int N;
Aluno novoAluno[N];
char st[10];
N=0;
while(fgets(st, 10, f)!=NULL)
{
novoAluno[N].numTeste=atoi(st);
fgets(st, 10, f);
novoAluno[N].nota=atof(st);
fgets(novoAluno[N].descricao, 50, f);
N++;
}
printf("Existem %d testes\n\n", N);
int i;
for(i=0;i<N;i++)
{
printf("Teste %d\n", novoAluno[i].numTeste);
printf("Nota: %.2f\n", novoAluno[i].nota);
printf("Descricao: %s\n", novoAluno[i].descricao);
}
fseek(f, 0, SEEK_SET);
}
void Adicionar(FILE *f)
{
int N;
printf("Quantos testes deseja inserir?");
scanf("%d", &N);
Aluno novoAluno[N];
for(int i=0;i<N;i++)
{
printf("Insira o numero do teste: ");
scanf("%d", &novoAluno[i].numTeste);
//printf("%d", novoAluno[i].numTeste);
fprintf(f, "%d\n", novoAluno[i].numTeste);
printf("Insira a nota: ");
scanf("%f", &novoAluno[i].nota);
//printf("%.2f", novoAluno[i].nota);
fprintf(f, "%.2f\n", novoAluno[i].nota);
printf("Insira detalhes(pratica, teoria...): ");
scanf("%s", novoAluno[i].descricao);
fprintf(f, "%s\n", novoAluno[i].descricao);
}
fseek(f, 0, SEEK_SET);
printf("\n");
printf("Todos os dados relativos aos testes foram inseridos.\n");
printf("****************************************************\n");
}
void Editar(FILE *f)
{
int N, K;
char st[10];
Aluno novoAluno[N];
printf("Qual o teste que deseja editar? ");
scanf("%d", &K);
N=0;
while(fgets(st, 10, f)!=NULL)
{
novoAluno[N].numTeste=atoi(st);
fgets(st, 10, f);
novoAluno[N].nota=atof(st);
fgets(novoAluno[N].descricao, 50, f);
N++;
}
printf("Existem %d testes\n\n", N);
if(K==1)
{
fseek(f, 0, SEEK_SET);
}
else if(K>1)
{
fseek(f, K*(sizeof(novoAluno[0].numTeste)+sizeof(novoAluno[0].numTeste)+sizeof(novoAluno[0].nota)+sizeof(novoAluno[0].descricao)), SEEK_SET);
}
printf("Introduza a nota: ");
scanf("%f", &novoAluno[K-1].nota);
fprintf(f, "%.2f", novoAluno[K-1].nota);
printf("Teorica ou Pratica? ");
scanf("%s", novoAluno[K-1].descricao);
fprintf(f, "%s", novoAluno[K-1].descricao);
}
void Remover()
{
}
int Menu(FILE *f)
{
int opcao;
printf(" Menu\n\n");
printf("1 --> Listar\n");
printf("2 --> Adicionar\n");
printf("3 --> Editar\n");
printf("4 --> Remover\n");
printf("5 --> Sair\n");
scanf("%d", &opcao);
switch(opcao)
{
case 1: Listar(f);break;
case 2: Adicionar(f); break;
case 3: Editar(f);break;
case 4: Remover();break;
case 5: printf("A fechar o programa!\n"); break;
default : printf("Opcao invalida!\n"); break;
}
return opcao;
}
int main()
{
char nomeFicheiro[50];
printf("Qual o nome do ficheiro a criar? ");
scanf("%s", nomeFicheiro);
char auxFicheiro[50];
sprintf(auxFicheiro, "%s.txt", nomeFicheiro);
FILE *f;
f=fopen(auxFicheiro, "r+");
if(f==NULL)
{
printf("Erro\n");
return 0;
}
int valorMenu;
do
{
valorMenu=Menu(f);
}while((valorMenu>=1)&&(valorMenu<=4));
return 0;
}