elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Fichero guarda basura en vez de int (en C)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Fichero guarda basura en vez de int (en C)  (Leído 1,433 veces)
locodeltacho

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Fichero guarda basura en vez de int (en C)
« en: 14 Septiembre 2015, 00:53 am »

Buenas gente! llevo un rato buscando una solución a un problema que me surgió haciendo la tarea de programación.
Me mandaron a hacer varias funciones con archivos. Una que cree un archivo, otra que lo abra, otra para agregar registros y una que los muestre.

Estoy bastaaaante perdido en el tema, pero logré que se cree el archivo y guarde algunos datos. El problema es que lo que es char lo guarda bien, pero lo que es int lo guarda como basura. (además de otros, como que no se hacer la función de "abrir", asi que decidi hacer un fopen en cada funcion xD)
Cuando estoy usando el programa


Despues de cerrar y leer de nuevo el archivo...



acá el codigo:
Main.c
Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "struct.h"
  4.  
  5. int main()
  6. {
  7.    menu();
  8. }
  9.  

Libreria
Código
  1. #ifndef STRUCT_H_INCLUDED
  2. #define STRUCT_H_INCLUDED
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. typedef struct{
  8.                char nombre[45];
  9.                char apellido[45];
  10.                int edad;
  11.                int nreg;
  12. }t_registro;
  13.  
  14. void menu();
  15. int CrearArchivo();
  16. int AbrirArchivo(t_registro *reg);
  17. int AgregarRegistro(t_registro *reg);
  18. int MostrarRegistro(t_registro const *reg);
  19.  
  20. #endif // STRUCT_H_INCLUDED
  21.  

Funciones
Código
  1. #include "struct.h"
  2.  
  3. void menu()
  4. {
  5.    char sele;
  6.  
  7.    t_registro registro;
  8.  
  9.    do
  10.    {
  11.        puts("\t \n Menu de Opciones");
  12.        puts("\t \n a) Crear archivo");
  13.        puts("\t \n b) Abrir archivo");
  14.        puts("\t \n c) Agregar registro");
  15.        puts("\t \n d) Mostrar registro");
  16.        puts("\t \n e) Buscar registro por apellido");
  17.        puts("\t \n 0) Salir");
  18.        fflush(stdin);
  19.        scanf("%c",&sele);
  20.        if((sele>='a'&&sele<='e')||sele=='0')
  21.        {
  22.  
  23.  
  24.            switch(sele)
  25.            {
  26.            case 'a':
  27.                CrearArchivo(&registro);
  28.                break;
  29.            case 'b':
  30.                AbrirArchivo(&registro);
  31.                break;
  32.            case 'c':
  33.                AgregarRegistro(&registro);
  34.                break;
  35.            case 'd':
  36.                MostrarRegistro(&registro);
  37.                break;
  38.            case 'e':
  39.                BuscarApellido(&registro);
  40.                break;
  41.  
  42.            }
  43.            fflush(stdin);
  44.        }
  45.        else
  46.        {
  47.            printf("\n Opcion incorrecta. ... \n \n");
  48.            fflush(stdin);
  49.        }
  50.    }
  51.    while(sele!='0');
  52. }
  53. ////////////////
  54.  
  55. int CrearArchivo(t_registro *reg)
  56. {
  57.    FILE *pf;
  58.  
  59.    pf=fopen("archivo.dat","wb");
  60.    if(pf==NULL)
  61.    {
  62.        printf("\n No se pudo acceder");
  63.        return 0;
  64.    }
  65.    printf("\n Archivo creado! ");
  66.    fclose(pf);
  67.    return 1;
  68. }
  69.  
  70. ////////////////
  71.  
  72. int AbrirArchivo(t_registro *reg)
  73. {
  74.    FILE *pf;
  75.  
  76.    pf=fopen("archivo.dat","r+b");
  77.    if(pf==NULL)
  78.    {
  79.        printf("\n No se pudo acceder");
  80.        return 0;
  81.    }
  82.    printf("\n Se abrio el archivo!");
  83.    return 1;
  84.  
  85. }
  86.  
  87. ///////////////
  88.  
  89. int AgregarRegistro(t_registro *reg)
  90. {
  91.    FILE *pf;
  92.  
  93.   pf=fopen("archivo.dat","a+b");
  94.    if(pf==NULL)
  95.    {
  96.        printf("\n No se pudo acceder");
  97.        return 0;
  98.    }
  99.    printf("\n Ingrese datos a agregar..");
  100.  
  101.    printf("\n Nro Registro \t Nombre \t Apellido \t Edad \t \n");
  102.    fflush(stdin);
  103.    scanf("%d %s %s %d", &reg->nreg,reg->nombre,reg->apellido,&reg->edad);
  104.    fflush(stdin);
  105.    fwrite(&reg,sizeof(t_registro),1,pf);
  106.    fclose(pf);
  107.   return 1;
  108.  
  109. }
  110. ///////////////
  111.  
  112. int MostrarRegistro(t_registro const *reg)
  113. {
  114.    FILE *pf;
  115.  
  116.    pf=fopen("archivo.dat","rb");
  117.    if(pf==NULL)
  118.    {
  119.        printf("\n No se pudo acceder");
  120.        return 0;
  121.    }
  122.    printf("\n Datos hasta el momento \n");
  123.    printf("\n Nro Registro \t Nombre \t Apellido \t Edad \t \n \n");
  124.    fread(&reg,sizeof(t_registro),1,pf);
  125.    fflush(stdin);
  126.    while(!feof(pf))
  127.    {
  128.  
  129.        printf("\n %d \t\t %s \t\t %s \t %d",reg->nreg,reg->nombre,reg->apellido,reg->edad);
  130.        fread(&reg,sizeof(t_registro),1,pf);
  131.        fflush(stdin);
  132.    }
  133.    fclose(pf);
  134.    return 1;
  135. }
  136.  
  137.  

Si me pudieran señalar los errores, se los agradecería muchisimo
Saludos!


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Guarda basura al leer string desde un fichero.[RESUELTO]
Programación C/C++
utz 5 4,591 Último mensaje 14 Mayo 2012, 03:36 am
por durasno
¿Dónde se guarda el fichero y cómo consigo el ejecutable?
Programación C/C++
goto C 9 13,231 Último mensaje 21 Agosto 2013, 05:16 am
por flony
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines