C/Visual C - ejercicio de agenda

 
Vista:

ejercicio de agenda

Publicado por luis (1 intervención) el 29/05/2009 11:54:13
/* Programa de ficheros tipo menú, consistente en la gestión de una agenda de contactos. */
/* Se utiliza un fichero sobre el que se realizarán accesos secuenciales. */
/* La opción 4 (eliminar contacto) marcará el registro a eliminar de manera que no sea */
/* visualizado. */
/* La opción 6 (compactar fichero) eliminará del fichero los registros marcados como */
/* eliminados. */
/* NOTA: por simplicidad del código, se ha omitido el control de los errores en las */
/* operaciones de E-S (fopen, fread, fwrite, fseek) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char op=0, aux[50];
void listar (FILE *);
void buscar (FILE *);
void anadir (FILE *);
void eliminar (FILE *);
void compactar (FILE *);
/* Estructura del registro a utilizar */
struct s_agenda{
char nombre [50];
char tlf [20];
char dni [10];
int edad;
};
int main (void)
{
FILE * f_agenda;
/* Con este modo de apertura (r+) el fichero existe previamente,
aunque sea vacio. */
f_agenda=fopen("agenda.dat","r+");
while (op!='6')
{
system ("cls");
printf (" AGENDA: ");
printf ("1 - Listar contactos ");
printf ("2 - Buscar contacto ");
printf ("3 - Introducir contacto ");
printf ("4 - Eliminar contacto ");
printf ("5 - Compactar fichero ");
printf ("6 - Salir ");
printf (" Introduce opcion: ");
fflush (stdin);
scanf ("%c",&op);
switch(op)
{
case '1':
listar(f_agenda);
break;
case '2':
buscar(f_agenda);
break;
case '3':
anadir(f_agenda);
break;
case '4':
eliminar(f_agenda);
break;
case '5':
compactar(f_agenda);
break;
case '6':
printf(" Programa finalizado. ");
getch();
break;
default:
printf (" OPCION NO VALIDA!! ");
getch();
break;
}
}
fclose(f_agenda);
}
/******************************************************************/
void listar (FILE * pf)
{
int n;
struct s_agenda registro;
fseek(pf, 0, SEEK_SET);
n=fread(®istro, sizeof(struct s_agenda),1,pf);
while (n==1)
{
/* Sólo muestro los que no tienen la marca "eliminado" */
if (strcmp(registro.nombre,"eliminado")!=0)
{
printf (" ");
puts(registro.nombre);
puts(registro.tlf);
puts(registro.dni);
printf("%d ",registro.edad);
getch();
}
n=fread(®istro, sizeof(struct s_agenda),1,pf);
}
}
/******************************************************************/
void buscar (FILE * pf)
{
struct s_agenda registro;
fseek(pf, 0, SEEK_SET);
printf (" Introduce nombre:");
fflush (stdin);
gets (aux);
fread(®istro, sizeof(registro),1,pf);
while (!feof(pf))
{
/* Si encuentro el nombre, lo muestro con el resto de datos y salgo de la función. */
if (strcmp(registro.nombre, aux)==0)
{
printf (" ");
puts(registro.nombre);
puts(registro.tlf);
puts(registro.dni);
printf("%d ",registro.edad);
getch();
return;
}
fread(®istro, sizeof(registro),1,pf);
}
/* Sólo llego a esta instrucción en el caso de terminar el fichero sin encontrarlo */
printf (" Contacto no encontrado");
}
/******************************************************************/
void anadir (FILE * pf)
{
long n;
struct s_agenda registro, registro2;
/* Intentaré introducir el nuevo registro es un registro marcado como eliminado. */
/* Si no lo encuentro lo añadiré al final como un registro nuevo */
fseek (pf, 0, SEEK_SET);
printf (" Introduce nombre:");
fflush (stdin);
gets (registro2.nombre);
printf ("Introduce telefono:");
fflush (stdin);
gets (registro2.tlf);
printf ("Introduce DNI:");
fflush (stdin);
gets (registro2.dni);
printf ("Introduce edad:");
fflush (stdin);
scanf("%d",®istro2.edad);
n=fread(®istro, sizeof(registro),1,pf);
while (n==1)
{
if(strcmp(registro.nombre,"eliminado")==0)
{
/* Sobreescribimos el nuevo contacto en este registro y terminamos la función */
/* Antes he de retroceder el cursor un registro con fseek para posicionarme en */
/* el registro que acabo de leer con fread */
fseek(pf,-sizeof(registro),SEEK_CUR);
fwrite(®istro2,sizeof(registro2),1,pf);
return;
}
n=fread(®istro, sizeof(registro),1,pf);
}
/* Sólo llegaremos a esta linea si no hemos encontrado un registro eliminado */
fwrite(®istro2,sizeof(registro2),1,pf);
}
/******************************************************************/
void eliminar (FILE * pf)
{
struct s_agenda registro;
/* Esta función simplemente localiza el nombre en el fichero, y lo cambia como "eliminado" */
fseek(pf, 0, SEEK_SET);
printf (" Introduce nombre:");
fflush (stdin);
gets (aux);
fread(®istro, sizeof(registro),1,pf);
while (!feof(pf))
{
/* Si encuentro el nombre lo marco como borrado y salgo de la función */
if (strcmp(registro.nombre, aux)==0)
{
strcpy(registro.nombre,"eliminado");
fseek(pf,-sizeof(registro),SEEK_CUR);
fwrite(®istro, sizeof(registro),1,pf);
printf (" Contacto eliminado");
getch();
return;
}
fread(®istro, sizeof(registro),1,pf);
}
/* Si llego hasta aquí es que no lo he encontrado (no me he salido con return)*/
printf (" Contacto no encontrado");
getch();
}
/******************************************************************/
void compactar(FILE * pf)
{
struct s_agenda registro;
/* Este proceso consistirá en eliminar los posibles registros marcados como "eliminado" */
/* para así reducir el espacio del fichero y el número de accesos al mismo. */
/* Se usará un fichero auxiliar para crear un fichero sin estos registros. */
/* Posteriormente se renombrará el fichero auxiliar como el original. */
FILE * pf_auxiliar;
pf_auxiliar=fopen("auxiliar.dat","w");
fseek(pf, 0, SEEK_SET);
fread(®istro, sizeof(registro),1,pf);
while (!feof(pf))
{
/* Si no existe la marca "eliminado" paso el registro al fichero auxiliar */
if (strcmp(registro.nombre, "eliminado")!=0)
{
fwrite(®istro, sizeof(registro), 1,pf_auxiliar);
}
fread(®istro, sizeof(registro),1,pf);
}
/* Se cierran los ficheros para poder borrarlos y renombrarlos */
fclose(pf);
fclose(pf_auxiliar);
/* Borramos el fichero "agenda.dat" */
system("del agenda.dat");
/* Una vez creado el fichero "auxiliar.dat", lo renombramos como "agenda.dat" */
system("rename auxiliar.dat agenda.dat");
/* y lo abrimos de nuevo, para que el programa siga funcionando con normalidad */
pf=fopen("agenda.dat","r+");
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder