Problem auto counter id file in c

0

I have a problem with this function, I would need the id to auto-add each time I want to create a user, the function works, the problem is that when the program is closed and reopened the counter returns to 0 and does not at the value I had before, some help? Thanks.

#define maxchar 30
typedef struct{
int id;
char usuario[maxchar];  
char nombre[maxchar];  
char apellido[maxchar];  
char domicilio[maxchar];  
char localidad[maxchar];   
int eliminado; // indica 1 o 0 si el cliente fue eliminado  
}Cliente;

void reg_usuario ()  
{  
int cont=0;  
char control = 's';  
FILE* fichero ;   
Cliente cl; // creo un nuevo cliente de la estructura cliente

fichero=fopen("datos_usuarios","a+b");  
if(fichero==NULL)  
{  
    fichero=fopen("datos_usuarios","a+b");  
}  
  if(fichero!=NULL)  
  {  
    printf ("Menu de Ingreso de usuarios\n");   
    while(cont<30 && control == 's')   
    {    
     printf ("generando ID de usuario automaticamente...\n");    
     fflush(stdin);  
     idaux++;  
     cl.id = idaux;  
     printf("\nIngrese su usuario: ");  
     gets(cl.usuario);  
     printf ("\n Ingrese Nombre: ");  
     fflush(stdin);  
     gets(cl.nombre);  
     printf ("\n Ingrese Apellido: ");   
     fflush(stdin);   
     gets (cl.apellido);   
     printf ("\n Ingrese Domicilio: ");   
     fflush(stdin);   
     gets (cl.domicilio);   
     printf ("\n Ingrese Localidad:");   
     fflush(stdin);   
     gets (cl.localidad);   

     fwrite (&cl, sizeof (cl), 1, fichero);   
     printf ("desea cargar otro usuario? (s/n)");   
     fflush(stdin);  
     scanf("%c",&control);    
     cont ++;    
    }   

    fclose(fichero);    
  }   
}    
    
asked by Agustin Nicoloso 15.06.2017 в 21:52
source

1 answer

0

To keep your id between executions of the program, you have to save it in a file, database or similar. When leaving the program you can call a function void guardar(int id) open a file and save the id of the last registered user. When you start the program again you can call a int leer() function to recover the id. The problem with this is that if you exit the program abruptly, it will not save the changes. To solve this, you could save the incremented value in the id file every time you execute your reg_usuario function. For your case it seems that it is not important, but this solution has too much overhead due to the system calls to write to the file. An interesting optimization could be to load the file into memory.

    
answered by 16.06.2017 в 10:25