Thread: I need to get this code working with gcc (it works with dev-c++)

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    16

    I need to get this code working with gcc (it works with dev-c++)

    I don't know why it doesn't work. In dev-c++ I can do a search without any problems. In gcc it doesn't eve works. I really need to get this working with gcc.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    //"ID" es como el numero de serie del producto...
    
    struct producto 
    {
       char nombre[30];
       char precio[10];
       char tipo[20];
       char receta[3];
       char disponibilidad[10];
       char necesidad[2];
       int ID;
       struct producto *SGTE;
    } registro;
    
    int menu(void);
    
    void crear(struct producto **cabeza);
    int vacia(struct producto *cabeza);
    void listar(struct producto *cabeza,int opcion);
    void visualizar(struct producto *cabeza);
    void visualizarRecursivo(struct producto *actual);
    void insertar(struct producto **cabeza);
    void borrar(struct producto **cabeza);
    void liberar(struct producto **cabeza);
    void crearlog(struct producto **cabecera);
    void mostrarlog(void);
    
    void crearlog(struct producto **cabecera)
    {
         struct producto *actual,*sucesor;
         actual=*cabecera;
         FILE *log;
         log=fopen("log.txt","a");
    
         if( log == NULL )
         {
           printf("Archivo no existe");
           getchar();
           getchar();
         }
         else {
         while(actual!=NULL){
           fprintf( log, "%s %s %s %s %s %s\n" ,actual->nombre,actual->precio,actual->tipo,actual->receta,actual->disponibilidad,actual->necesidad);
           actual=actual->SGTE;
         }
         fclose(log);
              }
    }
    
    void mostrarlog(void)
    {
         FILE *p;
         char linea[60];
         p=fopen("log.txt","r");
         if( p == NULL )
         {
           printf("Archivo no existe");
           getchar();
         }
         else{
         printf("Producto / Precio / Tipo / Receta / Disponibilidad / NivelNecesidad\n\n");
    
         while(!feof(p)){
           fgets(linea,60,p);
           printf("%s",linea);  
           fflush(stdout);
           }
         fclose(p);     
         getchar();
         }
      }
    
    struct prod 
    {
       char precio[10];
       char tipo[20];
       char receta[3];
       char disponibilidad[10];
       char necesidad[2];
       int ID;
       struct prod *AFTER;
    };
    
    struct Nodo {
           char nombre[30];
           int cont;
           struct Nodo *otro;
           struct prod *next;
           };
    
    typedef struct {
    	int longitud;  	
    	struct Nodo *primero, *nodo;
    }tHEAD, *HEAD;
    
    HEAD NEW(void)
    {
       HEAD pHEAD=(HEAD)malloc(sizeof(tHEAD));
       pHEAD -> primero = NULL;
       pHEAD -> nodo = NULL;
       pHEAD -> longitud = 0;
       return pHEAD;
    }
    
    void insertarNodo(HEAD HEAD, char elem[30])
    {
     struct Nodo *p,*q;
     if(HEAD->primero==NULL){
         p=(struct Nodo *)malloc(sizeof(struct Nodo));   
         strcpy(p -> nombre,elem);
         p -> otro = HEAD -> primero;
    	 HEAD -> primero = p;
    	 HEAD -> nodo = HEAD->primero;
    	 HEAD -> nodo -> next = NULL;
    	 HEAD -> nodo -> cont = 0;
    	 HEAD -> longitud ++;
      }
    
     else {
    
           q=HEAD->primero;
           if(strcmp(q->nombre,elem)!=0){
           while(q->otro!=NULL&&(strcmp(q->otro->nombre,elem)!=0))
                q=q->otro;
    
           if(q->otro==NULL){
                 p=(struct Nodo *)malloc(sizeof(struct Nodo));   
                 strcpy(p -> nombre,elem);
    
                 p -> otro = HEAD -> primero;
    	         HEAD -> primero = p;
    	         HEAD -> nodo = HEAD->primero;
             	 HEAD -> nodo -> next = NULL;
            	 HEAD -> longitud ++; 
            	 HEAD -> nodo -> cont = 0;
              }      
          }
      }
    }
    
    void FIND(HEAD HEAD)
    {
         struct Nodo *p=HEAD->primero;
         struct prod *q;
         char find[30];
         printf("Medicamento a buscar: ");
         scanf("%s", find);
    
         while(strcmp(find,p->nombre)!=0)
         {
            p=p->otro;
            q=p->next;
         }
         printf("\t%s\n",p->nombre);
         printf("\tPrecio: $%s\n",q->precio);
         printf("\tClasificacion: %s\n",q->tipo);
         printf("\tReceta: %s\n",q->receta);
         printf("\tDisponibilidad:%s\n",q->disponibilidad);
         printf("\tNivel de Necesidad: %s\n",q->necesidad);
         getchar();
         menu();
    }
    
    void PASTE(HEAD HEAD,char nombre[30],char precio[10],char tipo[20],char receta[3],char disponibilidad[10],char necesidad[2])
    {    
         struct Nodo *p=HEAD->primero;
         struct prod *q,*nodoInfo;
    
         while(p!=NULL){
            if(strcmp(p->nombre,nombre)==0)
            {
                  q=p->next;
    
                  if(q==NULL){
                     nodoInfo=(struct prod *)malloc(sizeof(struct prod));
                     p->next=nodoInfo;
    
                     strcpy(nodoInfo->precio,precio);
                     strcpy(nodoInfo->tipo,tipo);
                     strcpy(nodoInfo->receta,receta);
                     strcpy(nodoInfo->disponibilidad,disponibilidad);
                     strcpy(nodoInfo->necesidad,necesidad);
                     nodoInfo->AFTER=NULL;
                     p->cont++;
                     }
    
                  else{
                     while(q->AFTER!=NULL){
                        q=q->AFTER;
                        }
                     if(q->AFTER==NULL){
                        nodoInfo=(struct prod *)malloc(sizeof(struct prod));
                        q->AFTER=nodoInfo;
                        strcpy(nodoInfo->precio,precio);
                        strcpy(nodoInfo->tipo,tipo);
                        strcpy(nodoInfo->receta,receta);
                        strcpy(nodoInfo->disponibilidad,disponibilidad);
                        strcpy(nodoInfo->necesidad,necesidad);
                        nodoInfo->AFTER=NULL;
                        p->cont++;          
                        }
                   }      
               }
            p=p->otro;
            }
         }
    
    void ENLAZAR()
    {
          FILE *fichero;
          fichero=fopen("log.txt","r");
          char nombre[30],precio[10],tipo[20],receta[3],disponibilidad[10],necesidad[2]; 
          HEAD lista;
          lista=NEW();    
    
          while( (!feof(fichero)) )
          {
                        fscanf(fichero,"%[^ ]",nombre);
                        insertarNodo(lista,nombre);
                        getc(fichero);
                        fscanf(fichero,"%[^ ]",precio);
                        getc(fichero);
                        fscanf(fichero,"%[^ ]",tipo);
                        getc(fichero);
                        fscanf(fichero,"%[^ ]",receta);
                        getc(fichero);
                        fscanf(fichero,"%[^ ]",disponibilidad);
                        getc(fichero);
                        fscanf(fichero,"%[^\n]",necesidad);
                        PASTE(lista,nombre,precio,tipo,receta,disponibilidad,necesidad);
                        getc(fichero);
          }
          fclose(fichero);
          system("CLS");
          FIND(lista);
    }
    
    int main()
    {
       struct producto *cabecera;
       int opcion;
       crear(&cabecera);
    
       do
       {
          opcion=menu();
          switch(opcion)
          {
    	 case 1: listar(cabecera,1);
    		 break;
    	 case 2: insertar(&cabecera);
    		 break;
    	 case 3: ENLAZAR();
    		 break;
    	 case 4: liberar(&cabecera);
    		 break;
    	 case 5: crearlog(&cabecera); 
    		 break;
    	 case 6: system("CLS"); mostrarlog();
    		 break;
          }
       } while (opcion);  /* opcion != 0 */
    }
    
    void crear(struct producto **cabecera)
    {
       *cabecera = NULL;
    }
    
    int vacia(struct producto *cabecera)
    {
       if (cabecera==NULL)
          return 1;
       else
          return 0;
    }
    
    void listar(struct producto *cabecera,int opcion)
    {
       if (vacia(cabecera))
          printf("\n\nNo ha escrito nada.\n");
       else
       {
          system("cls");
          printf("LISTADO\n");
          printf("-------\n\n");
          if (opcion==1)
    	     visualizar(cabecera);
       }
       getchar();
    }
    void visualizar(struct producto *cabecera)
    
    {
       struct producto *actual;  /* recorre la lista */
       int n=0;
       actual = cabecera;
    
       while (actual!=NULL)
       {
          printf("\nNombre: %s",actual->nombre);
          printf("\nPrecio: $%s",actual->precio);
          printf("\nClasificacion: %s",actual->tipo);
          printf("\nReceta: %s",actual->receta);
          printf("\nDisponibilidad: %s",actual->disponibilidad);
          printf("\nNivel de Necesidad: %s",actual->necesidad);
          printf("\nID: %i",actual->ID);
          printf("\n--------------------\n");
          actual= actual->SGTE;
       }
    }
    
    /************************ Función insertar() ************************/
    /*
       Propósito:  Pide un número al usuario y lo inserta como nodo en la
       lista de forma que se mantenga el orden ascendente de la misma.
       Parámetros: Puntero cabeza de lista por referencia.
       Devuelve:   Nada.
    
    */
    
    /********************************************************************/
    void insertar(struct producto **cabecera)
    {
       struct producto *predecesor,*sucesor,*nuevo;
       system("cls");
    
       FILE *fichero;
    
       fichero = fopen( "log.txt", "a" );
       printf("INSERTAR\n");
       printf("---------\n\n");
       nuevo = (struct producto *) malloc(sizeof(struct producto));
       printf("Nombre: "); fflush(stdout);
       gets(nuevo->nombre); fflush(stdin);
       printf("Valor: "); fflush(stdout);
       gets(nuevo->precio); fflush(stdin);
       printf("Clasificacion: "); fflush(stdout);
       gets(nuevo->tipo); fflush(stdin);
       printf("Requiere receta (SI/NO): "); fflush(stdout);
       gets(nuevo->receta); fflush(stdin);
       printf("Disponibilidad: "); fflush(stdout);
       gets(nuevo->disponibilidad); fflush(stdin);
       printf("Nivel de necesidad (1/10): "); fflush(stdout);
       gets(nuevo->necesidad); fflush(stdin);
       printf("Introduzca el ID: "); fflush(stdout);
       scanf("%d",&nuevo->ID); fflush(stdin);
    
       if (vacia(*cabecera) || nuevo->ID < (*cabecera)->ID)
       {
          nuevo->SGTE = *cabecera;
          *cabecera = nuevo;
       }
       else  /* caso general */
       {
          predecesor = *cabecera;
          sucesor = predecesor->SGTE;
          while (sucesor!=NULL && sucesor->ID <= nuevo->ID)
          {
    	 predecesor = sucesor;
    	 sucesor = sucesor->SGTE;
          }
          predecesor->SGTE = nuevo;
          nuevo->SGTE = sucesor;
       }
    }
    
    
    
    
    
    /************************ Función liberar() *************************/
    
    /*
    
       Propósito:  Libera la memoria ocupada por la lista de forma iterativa.
    
       Parámetros: Puntero cabeza de lista por referencia.
    
    
    
    */
    
    /********************************************************************/
    
    void liberar(struct producto **cabecera)
    {
       struct producto *actual,*sucesor;
    
       actual = *cabecera;
       while (actual!=NULL)
    
       {
          sucesor = actual->SGTE;
          free(actual);
          actual = sucesor;
       }
       *cabecera = NULL;
    }
    
    
    
    int menu()
    {
       int opcion;
    
       system("cls");
       printf("-------------------------\n\n");
       printf("1.- Visualizar lo que ha escrito \n");
       printf("2.- Insertar producto\n");
       printf("3.- Buscar producto\n");
       printf("4.- Deshacer cambios\n");
       printf("5.- Guardar cambios en log.txt\n");
       printf("6.- Revisar log.txt\n");
       printf("0.- Salir.\n\n\n");
       printf("Introduce una opcion: ");
       scanf("%d",&opcion);
       fflush(stdin);
       return opcion;
    }
    it reads from this file (named log.txt)

    Code:
    ASPIRINA 1000 ANALGESICO NO ALTA 8
    IBUPROFENO 530 ANALGESICO NO ALTA 9
    CELECOXIB 3490 ANALGESICO SI MEDIA 5
    DICLOFENACO 690 ANALGESICO SI ALTA 7
    BENZODIAZEPINAS 7800 ANSIOLITICO SI MEDIA 6
    CLONAZEPAM 5950 ANSIOLITICO SI ALTA 7
    DIAZEPAM 4900 ANSIOLITICO SI ALTA 8
    ALBENDAZOL 7800 ANTIHELMINTICO SI MEDIA 9
    MEBENDAZOL 10900 ANTIHELMINTICO SI BAJA 9
    SURANIM 20900 ANTIHELMINTICO SI MEDIA 8
    NICLOSAMIDA 7500 ANTIHELMINTICO SI ALTA 9
    KANTREX 7700 ANTIBIOTICO SI ALTA 5
    AMIKIN 5500 ANTIBIOTICO SI MEDIA 7
    TOLEXINE 13900 ANTIBIOTICO SI MEDIA 8
    CIPROBAY 5500 ANTIBIOTICO SI BAJA 4
    CLOXACILINA 540 ANTIBIOTICO SI BAJA 7
    AVELOX 3600 ANTIBIOTICO SI ALTA 3
    SYNCERCID 9000 ANTIBIOTICO SI MEDIA 5
    MIFEPRISTONA 20900 ANTICONCEPTIVO SI MEDIA 4
    YUPZENOL 3800 ANTICONCEPTIVO SI ALTA 6
    LEVONORGESTREL 10000 ANTICONCEPTIVO SI MEDIA 5
    METOTREXATO 19000 ANTIBIOTICO SI BAJA 4
    TAPSIN 1000 ANALGESICO NO ALTA 10
    FOLISANIN 3000 ANALGESICO NO MEDIA 8
    Last edited by medeshago; 12-21-2008 at 08:46 PM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Since dev-c++ uses gcc as its compiler, your statement of the problem cannot actually be true. What problems are you seeing?

  3. #3
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Dev-C++ does use gcc (MinGW)...

    1. Don't use feof() to control loops
    2. Don't use gets()
    3. Don't fflush(stdin)

    The reasons why are found in the FAQ.

    Try some debugging / a more specific answer -- it's pretty hard to read something that isn't in English and try work out what it does

  4. #4
    Registered User
    Join Date
    Oct 2008
    Posts
    16
    asdf.c:38: aviso: variable ‘sucesor’ sin usar

    That's the problem I'm having. When I try to search throught the list I get this:
    Medicamento a buscar: ASPIRINA
    ASPIRINA
    Precio: $(null)
    Segmentation fault

    I just checked and it works in windows, it doesn't in linux. Don't know what it is.
    Last edited by medeshago; 12-21-2008 at 08:48 PM.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    And what is line 38?

    And I'm not sure why you have a linked list of products, and nodes, and prods, and HEADs.

  6. #6
    Registered User
    Join Date
    Oct 2008
    Posts
    16
    Quote Originally Posted by tabstop View Post
    And what is line 38?

    And I'm not sure why you have a linked list of products, and nodes, and prods, and HEADs.
    void crearlog(struct producto **cabecera)
    {
    struct producto *actual,*sucesor; //line 38
    actual=*cabecera;
    FILE *log;

    I didn't write this code, it's from the guy I'm doing this work with.

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Well the warning is telling you that you went to all the trouble to make a variable called sucesor and then don't ever use it. Whether you thought you needed it or not, I don't know.

    Only one person, eh? I would've thought it would've taken three different people working in isolation and then combining their efforts to get something like this.

    As to the error, the Windows->Linux part and fflush(stdin) is the key. fflush(stdin) is meaningless, according to the C standard. Windows uses it to discard extraneous input; Linux does not. If you plan to have this program work in Linux, you will have to use real input gathering routines -- which means no gets, and no fflush(stdin). What you want is most likely fgets.

  8. #8
    Registered User
    Join Date
    Oct 2008
    Posts
    16
    I removed every fflush(stdin) and still doesn't work.

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Yes -- you still have to read things in correctly, as opposed to incorrectly as you are doing now. (Hint: There is no way to use gets correctly.)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Resizing a triangle. Why is my code not working?
    By gozu in forum Windows Programming
    Replies: 2
    Last Post: 01-20-2007, 06:40 PM
  2. compile c code using -00 option of gcc
    By George2 in forum Tech Board
    Replies: 1
    Last Post: 08-29-2006, 03:47 AM
  3. Replies: 2
    Last Post: 02-14-2006, 11:08 AM
  4. How Do u See if a code works
    By Nos in forum C++ Programming
    Replies: 11
    Last Post: 08-05-2005, 01:34 PM
  5. Sphere code not working
    By VirtualAce in forum Game Programming
    Replies: 2
    Last Post: 10-03-2004, 07:29 AM