#include <stdio.h>
#include <stdlib.h>
struct tagCursoFile
{
char nome;
char descricao;
int ciclo;
};
struct tagCursoMem
{
char nome;
char descricao;
int ciclo;
struct tagCursoMem* pNext;
};
int MainMenu();
void AddToHead(struct tagCursoMem** pAuxHead, struct tagCursoMem* pAuxNew);
//struct tagCursoMem* ProcMaisVelho(struct tagCursoMem* pAux);
void GravarFile(int nSatus, struct tagCursoMem* pAux);
void lerdados(struct tagCursoMem* pAux,struct tagCursoMem* pAuxNew);
int main()
{
int opc, nAlterado = 0, nCntAlunos = 0;
FILE* pFile;
struct tagCursoFile cursoFile;
struct tagCursoMem* pHead = NULL;
struct tagCursoMem* pNew, *pAux;
if((pFile = fopen("alunos.data", "rb")) != NULL) {
while(fread(&cursoFile, sizeof(struct tagCursoFile), 1, pFile) != 0) {
pNew = (struct tagCursoMem*)malloc(sizeof(struct tagCursoMem));
pNew->pNext = NULL;
pNew->nome = cursoFile.nome;
pNew->descricao = cursoFile.descricao;
pNew->ciclo = cursoFile.ciclo;
AddToHead(&pHead, pNew);
nCntAlunos++;
}
printf("Foram lidos %d registos", nCntAlunos);
fclose(pFile);
}
do {
opc = MainMenu();
switch(opc) {
case 1:
pNew = (struct tagCursoMem*)malloc(sizeof(struct tagCursoMem));
pNew->pNext = NULL;
printf("Indique o nome do curso:\n");
scanf("%s", &pNew->nome);
printf("Indique a descricao:\n");
scanf("%s", &pNew->descricao);
printf("Indique o ciclo:\n");
scanf("%d", &pNew->ciclo);
AddToHead(&pHead, pNew);
nAlterado = 1;
break;
case 2:
GravarFile(nAlterado, pHead);
nAlterado = 0;
break;
case 4:
system("cls");
pFile=fopen("alunos.data","r");
int num;
fread(&num,sizeof(int),1,pFile);
/* read a line */
fclose ( pFile );
system("pause");
/* close the file */
fclose(pFile);
return 0;
break;
/*
case 3:
if(((pAux = ProcMaisVelho(pHead)) != NULL))
printf("O aluno mais velho tem o numero %d", pAux->nNumero);
break;
*/
case 0:
break;
default:
printf("Opcao invalida!");
}
}while(opc != 0);
GravarFile(nAlterado, pHead);
return 0;
}
int MainMenu()
{
int sel;
puts("\n\n1 - Inserir aluno");
puts("2 - Gravar no ficheiro");
puts("3 - Aluno mais velho");
puts("4 - Ler Alunos");
puts("\n0 - Sair");
scanf("%d", &sel);
return sel;
}
void AddToHead(struct tagCursoMem** pAuxHead, struct tagCursoMem* pAuxNew)
{
if(*pAuxHead != NULL)
pAuxNew->pNext = *pAuxHead;
*pAuxHead = pAuxNew;
}
/*
struct tagCursoMem* ProcMaisVelho(struct tagCusoMem* pAux)
{
struct tagCursoMem *pMaisVelho;
if(pAux != NULL)
pMaisVelho = pAux; // nó inicial de comparação
else
return NULL;
while(pAux != NULL) {
if(pMaisVelho->nIdade < pAux->nIdade)
pMaisVelho = pAux;
pAux = pAux->pNext;
}
return pMaisVelho;
}
*/
void GravarFile(int nStatus, struct tagCursoMem* pAux)
{
FILE* pFile;
struct tagCursoFile Curso;
if(nStatus == 1) {
if((pFile = fopen("alunos.data", "w")) != NULL) {
while(pAux != NULL) {
Curso.nome = pAux->nome;
Curso.descricao = pAux->descricao;
Curso.ciclo = pAux->ciclo;
fwrite(&Curso, sizeof(struct tagCursoFile), 1, pFile);
pAux = pAux->pNext;
}
}
fclose(pFile);
}
}