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

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Problema Fwrite
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema Fwrite  (Leído 2,440 veces)
kristian_5

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Problema Fwrite
« en: 1 Junio 2013, 15:46 pm »

Hola pues estoy haciendo un programa de una base de datos de una frutería utilizando ficheros. Mi problema es que el Fwrite no me lo acaba de hacer bien. Y ya me estoy desesperando un poco porque soy incapaz de ver la razón.

Haber si podéis echarme una mano! Gracias.   

Aquí dejo el código en principio solo es de la función.

La cuestión de esta función es hacer compras automáticas desde un archivo "comprasxx".txt le pongo "manzanas 2" y lo que debe hacer es aumentar el inventario.



Código:
void compra_auto( int cont){    
        char fichero[10];
        char fruta[20];
        int cantidad = 0;
        int existe = 0;
        int i;
        struct tfruteria frut;
       
        if ((loog = fopen("log.txt", "a+")) == NULL){
        printf ("Error en obertura del fitxer per a lectura.\n");
        }
       
        printf ("Dame el nombre del fichero: ");
        scanf ("%s", fichero);
       
        cmp = fopen (fichero, "r");
        if (!cmp){
        cmp = fopen("compras00.txt", "r");           
        printf ("No existe el archivo se cogera el archivo por defecto\n");
        fscanf (cmp, "%s  %d", fruta, &cantidad);
        fclose (cmp);
           
           if ((dat = fopen("fruites.dat", "rb+")) == NULL){
            } else{
            fflush(stdin);
            rewind(dat);
            fread (&frut, Mida, 1, dat);
            i=1;
            while (!feof(dat)){
                  if(strcmp(fruta,frut.nom)==0){
                       printf ("La fruta existe!!\n");             
                       existe ++;
                       fprintf(loog,"Compra;%d;OK;%d;%d;%d\n",i,frut.quantitat, cantidad, frut.quantitat+cantidad);
                       fclose (loog); 
                       frut.quantitat=frut.quantitat+cantidad;
                       printf ("Ahora el estoc de %s es de: %d", frut.nom, frut.quantitat);
                       } //if si fruta existe
                       i++;
                        fread (&frut, Mida, 1, dat);
                        }//while
            if(existe == 0){
            printf ("La fruta no existe!!\n");   
            }else if (existe == 1){
             rewind(dat);
                       if(fwrite(&frut, Mida,1, dat) == 1)       
                       printf("\n Fruita modificada!! ");     
                       }else{
                       printf("No he pogut escriure el registre al buffer del fitxer\n");
                       fclose (dat);
                       }
                       }
                                     
                    }else{
                     printf ("El fichero si que existe se realizara las opciones oportunas\n");
                    fscanf (cmp, "%s  %d", fruta, &cantidad);
        fclose (cmp);
           
           if ((dat = fopen("fruites.dat", "rb+")) == NULL){
            } else{
            fflush(stdin);
            rewind(dat);
            fread (&frut, Mida, 1, dat);
            while (!feof(dat)){
                  if(strcmp(fruta,frut.nom)==0){
                       printf ("La fruta existe!!\n");             
                       existe ++;
                       frut.quantitat=frut.quantitat+cantidad;
                       printf ("Ahora el estoc de %s es de: %d", frut.nom, frut.quantitat);
                       } //if si fruta existe
                        fread (&frut, Mida, 1, dat);
                        }//while
            if(existe == 0){
            printf ("La fruta no existe!!\n");   
            }else if (existe == 1){
           rewind(dat);
                       if(fwrite(&frut, Mida,1, dat) == 1)       
                       printf("\n Fruita modificada!! ");     
                       }else{
                       printf("No he pogut escriure el registre al buffer del fitxer\n");
                       fclose (dat);
                       }
                     }
                     }//else
                     }//funcion   
             
   




En línea

aguml


Desconectado Desconectado

Mensajes: 378



Ver Perfil
Re: Problema Fwrite
« Respuesta #1 en: 10 Junio 2013, 00:13 am »

que lio de codigo, todo se ve sin identar al menos donde lo estoy viendo. De todos modos creo que si lo que quieres es simplemente leer un fichero en busca de un valor concreto y si existe incrementas x pues te sobra la mitad del codigo. Yo es que no termino de entender para que abres y cierras tanto los ficheros y para que tantos. Yo lo que haria seria abrir el fichero y primero de nada me iria al final del fichero y luego obtendria la posicion, eso se hace con fseek y ftell y el valor obtenido lo divido entre el tamaño de la estructura para obtener el numero de entradas y luego en un for uso ese valor como limite para buscar el nombre de la fruta usando fread para rellenar la estructura y luego si lo encuentra le sumo el valor que sea y como tengo el valor donde fue encontrado pues me posiciono ahi en el fichero y con fwrite machaco ese registro. Para hacerlo asi tienes que haber creado el fichero con el mismo formato que lo estes leyendo ya que si para crearlo usas fprint y para luego leerlo usas fread no te va a ir bien. Busca informacion sobre archivos de acceso aleatorio en C.


En línea

aguml


Desconectado Desconectado

Mensajes: 378



Ver Perfil
Re: Problema Fwrite
« Respuesta #2 en: 12 Junio 2013, 11:08 am »

No he podido responderte antes. Prueba este codigo a ver si te sirve:

Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct stRegistro {
  6.   int ID;
  7.   char nombre[25];
  8.   int cantidad;
  9. };
  10.  
  11. int Menu(void);
  12. void ChangeStock(char *operacion, struct stRegistro *reg);
  13. void MostrarCabecera(void);
  14. void MostrarProducto(long n, struct stRegistro *reg);
  15. long LeeNumero(void);
  16. void Borrar(FILE **fa, long numero);
  17. int Size(FILE **fa, int tam);
  18. //--------------------------------------------------------------------------
  19.  
  20. int main()
  21. {
  22.   struct stRegistro reg;
  23.   struct stRegistro aux;
  24.   char nombre[25];
  25.   FILE *fa;
  26.   int i, opcion, nRegistros, encontrado, ID;
  27.   long numero;
  28.   fa = fopen("stock.dat", "r+b");          // Este modo permite leer y escribir
  29.   if(!fa) fa = fopen("stock.dat", "w+b");  // si el fichero no existe, lo crea.
  30.   do {
  31.      opcion = Menu();
  32.      switch(opcion) {
  33.         case '1': // Añadir o incrementar el stock
  34.            encontrado = 0;
  35.            ChangeStock("Añadir al stock", &aux);
  36.            nRegistros = Size(&fa, sizeof(struct stRegistro));
  37.            for(i=0; i<nRegistros; i++)
  38.            {
  39.                fread(&reg,sizeof(struct stRegistro),1,fa);
  40.                if(strcmp(aux.nombre, reg.nombre) == 0)
  41.                {
  42.                        reg.cantidad += aux.cantidad;
  43.                        fseek(fa,i*sizeof(struct stRegistro),SEEK_SET);
  44.                        fwrite(&reg, sizeof(struct stRegistro), 1, fa);
  45.                        encontrado = 1;
  46.                        break;
  47.                }
  48.            }
  49.            if(encontrado == 0)
  50.            {
  51.                if(nRegistros == 0)
  52.                        ID = 0;
  53.                else
  54.                {
  55.                        fseek(fa, 0, nRegistros);
  56.                        fread(&reg,sizeof(struct stRegistro), 1, fa);
  57.                        ID = reg.ID + 1;
  58.                }
  59.                fseek(fa, 0, SEEK_END);
  60.                aux.ID = ID;
  61.                fwrite(&aux, sizeof(struct stRegistro), 1, fa);
  62.            }
  63.            break;
  64.         case '2': // Ventas de stockaje
  65.            encontrado = 0;
  66.            ChangeStock("Venta de stockaje", &aux);
  67.            nRegistros = Size(&fa, sizeof(struct stRegistro));
  68.            fseek(fa, 0, SEEK_SET);
  69.            for(i=0; i<nRegistros; i++)
  70.            {
  71.                fread(&reg,sizeof(struct stRegistro),1,fa);
  72.                if(strcmp(aux.nombre, reg.nombre) == 0)
  73.                {
  74.                        encontrado = 1;
  75.                        if(aux.cantidad <= reg.cantidad)
  76.                        {
  77.                                reg.cantidad -= aux.cantidad;
  78.                                fseek(fa,i*sizeof(struct stRegistro),SEEK_SET);
  79.                                fwrite(&reg, sizeof(struct stRegistro), 1, fa);
  80.                        }else{
  81.                                printf("No hay suficiente stockaje de ese producto para esta venta.\n");
  82.                                MostrarCabecera();
  83.                                MostrarProducto(i, &reg);
  84.                                printf("|---------|-------------------------|--------|\n\n");
  85.                                system("PAUSE");
  86.                        }
  87.                        break;
  88.                }
  89.            }
  90.            if(encontrado == 0)
  91.            {
  92.                printf("No se puede encontrar el producto indicado.\n\n");
  93.                system("PAUSE");
  94.            }
  95.            break;
  96.         case '3': // Mostrar stock de un producto por su ID
  97.            encontrado = 0;
  98.            system("cls");
  99.            printf("Buscar stock por ID: ");
  100.            ID = LeeNumero();
  101.            nRegistros = Size(&fa, sizeof(struct stRegistro));
  102.            for(i=0; i<nRegistros; i++)
  103.            {
  104.                fread(&reg,sizeof(struct stRegistro),1,fa);
  105.                if(ID == reg.ID)
  106.                {
  107.                        encontrado = 1;
  108.                        MostrarCabecera();
  109.                        MostrarProducto(i, &reg);
  110.                        break;
  111.                }
  112.            }
  113.            if(encontrado == 0)
  114.            {
  115.                printf("No se puede encontrar el producto indicado.\n\n");
  116.            }
  117.            else
  118.            {
  119.                printf("|---------|-------------------------|--------|\n\n");
  120.            }
  121.            system("PAUSE");
  122.            break;
  123.         case '4': // Mostrar stock de un producto por su nombre
  124.            encontrado = 0;
  125.            system("cls");
  126.            printf("Buscar stock por nombre: ");
  127.            fgets(nombre,25,stdin);
  128.            for(i = strlen(nombre)-1; i && nombre[i] < ' '; i--)
  129.                nombre[i] = 0;
  130.            nRegistros = Size(&fa, sizeof(struct stRegistro));
  131.            for(i=0; i<nRegistros; i++)
  132.            {
  133.                fread(&reg,sizeof(struct stRegistro),1,fa);
  134.                if(strcmp(nombre, reg.nombre) == 0)
  135.                {
  136.                        encontrado = 1;
  137.                        MostrarCabecera();
  138.                        MostrarProducto(i, &reg);
  139.                        break;
  140.                }
  141.            }
  142.            if(encontrado == 0)
  143.            {
  144.                printf("No se puede encontrar el producto indicado.\n\n");
  145.                system("PAUSE");
  146.            }
  147.            else
  148.            {
  149.                printf("|---------|-------------------------|--------|\n\n");
  150.            }
  151.            system("PAUSE");
  152.            break;
  153.         case '5': // Mostrar todo el stockaje
  154.            encontrado = 0;
  155.            rewind(fa);
  156.            numero = 0;
  157.            system("cls");
  158.            nRegistros = Size(&fa,sizeof(struct stRegistro));
  159.            if(nRegistros > 0)
  160.            {
  161.                encontrado = 1;
  162.                MostrarCabecera();
  163.                for(i = 0; i < nRegistros; i++)
  164.                {
  165.                        fread(&reg, sizeof(struct stRegistro), 1, fa);
  166.                        MostrarProducto(numero++, &reg);
  167.                }
  168.            }
  169.            if(encontrado == 0)
  170.            {
  171.                printf("No existen entradas en el registro.\n");
  172.            }
  173.            else
  174.            {
  175.                printf("|---------|-------------------------|--------|\n\n");
  176.            }
  177.            system("PAUSE");
  178.            break;
  179.         case '6': // Eliminar del stock
  180.            system("cls");
  181.            printf("Eliminar del stock: ");
  182.            numero = LeeNumero();
  183.            Borrar(&fa, numero);
  184.            break;
  185.      }
  186.   } while(opcion != '0');
  187.   fclose(fa);
  188.   return 0;
  189. }
  190. //--------------------------------------------------------------------------
  191.  
  192. // Muestra un menú con las opciones disponibles y captura una opción del usuario
  193. int Menu()
  194. {
  195.   char resp[20];
  196.   do {
  197.      system("cls");
  198.      printf("MENU PRINCIPAL\n");
  199.      printf("--------------\n\n");
  200.      printf("1- Añadir al stock\n");
  201.      printf("2- Venta\n");
  202.      printf("3- Buscar stock por su ID\n");
  203.      printf("4- Buscar stock por su nombre\n");
  204.      printf("5- Mostrar todo el stockaje\n");
  205.      printf("6- Eliminar producto del stock por su ID\n");
  206.      printf("0- Salir\n");
  207.      fgets(resp, 20, stdin);
  208.   } while(resp[0] < '0' && resp[0] > '6');
  209.   return resp[0];
  210. }
  211. //--------------------------------------------------------------------------
  212.  
  213. // Permite que el usuario introduzca un producto por pantalla
  214. void ChangeStock(char * operacion, struct stRegistro *reg)
  215. {
  216.   int i;
  217.   char numero[6];
  218.   system("cls");
  219.   printf("%s:", operacion);
  220.   printf("\n\n");
  221.   printf("Nombre: ");
  222.   fgets(reg->nombre, 25, stdin);
  223.   // la función fgets captura el retorno de línea, hay que eliminarlo:
  224.   for(i = strlen(reg->nombre)-1; i && reg->nombre[i] < ' '; i--)
  225.      reg->nombre[i] = 0;
  226.   printf("Cantidad: ");
  227.   fgets(numero, 6, stdin);
  228.   reg->cantidad = atoi(numero);
  229. }
  230. //--------------------------------------------------------------------------
  231.  
  232. // Muestra la cabecera de la tabla por pantalla
  233. void MostrarCabecera(void)
  234. {
  235.   printf("\n");
  236.   printf("|---------|-------------------------|--------|\n"
  237.          "|ID       |Nombre                   |Cantidad|\n"
  238.          "|---------|-------------------------|--------|\n");
  239. }
  240. //--------------------------------------------------------------------------
  241.  
  242. // Muestra un producto por pantalla
  243. void MostrarProducto(long n, struct stRegistro *reg)
  244. {
  245.        printf("|[%6ld] |%-25s| %4d   |\n", reg->ID, reg->nombre, reg->cantidad);
  246. }
  247. //--------------------------------------------------------------------------
  248.  
  249. // Lee un número suministrado por el usuario
  250. long LeeNumero()
  251. {
  252.   char numero[6];
  253.   fgets(numero, 6, stdin);
  254.   return atoi(numero);
  255. }
  256. //--------------------------------------------------------------------------
  257.  
  258. // Borra una entrada del archivo
  259. void Borrar(FILE **fa, long numero)
  260. {
  261.        struct stRegistro reg;
  262.        FILE *ftemp;
  263.        int largo, nRegistros, i;
  264.        rewind(*fa);
  265.        ftemp = fopen("temp.dat", "wb");
  266.        nRegistros = Size(*&fa,sizeof(struct stRegistro));
  267.        for(i=0; i<nRegistros; i++)
  268.        {
  269.                fread(&reg,sizeof(struct stRegistro),1,*fa);
  270.                if(numero != reg.ID)
  271.                {
  272.                        fwrite(&reg, sizeof(struct stRegistro), 1, ftemp);
  273.                }
  274.        }
  275.        fclose(ftemp);
  276.        fclose(*fa);
  277.        remove("stock.dat");
  278.        rename("temp.dat", "stock.dat");
  279.        *fa = fopen("stock.dat", "r+b");
  280. }
  281. //--------------------------------------------------------------------------
  282.  
  283. int Size(FILE **fa, int tam)
  284. {
  285.        int largo, n;
  286.        fseek(*fa, 0, SEEK_END);
  287.        largo = ftell(*fa);
  288.        n = largo / tam;
  289.        fseek(*fa, 0, SEEK_SET);
  290.        return n;
  291. }
  292. //--------------------------------------------------------------------------
  293.  
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Problemas con fwrite()
PHP
eLank0 2 1,902 Último mensaje 17 Enero 2007, 01:57 am
por eLank0
no me deja utilizar fwrite
PHP
CICOLO_111234 2 2,120 Último mensaje 23 Abril 2009, 18:20 pm
por дٳŦ٭
Problema para pasar una lista a fichero con Fwrite « 1 2 »
Programación C/C++
samur88 12 7,857 Último mensaje 21 Febrero 2011, 01:06 am
por samur88
fread y fwrite con clases
Programación C/C++
newone 4 4,665 Último mensaje 23 Junio 2011, 23:40 pm
por newone
Usos fwrite, fread
Programación C/C++
diegoCmC 4 5,298 Último mensaje 13 Septiembre 2012, 21:42 pm
por diegoCmC
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines