Modify a record of a structure in a file in C

1

I practically have to modify the field .baja of the structure of Cliente (this if it is modified correctly) and it turns out that all the other fields are also modified but with junk content. The idea is that they contain the same thing they had before but only changing the clienteBaja.baja . Thanks

int buscaCliente(FILE*archi)
{
  Cliente clientes;
  int buscar=0;
  int  posicion=-1;
  if(archi!=NULL)
{
    printf("Ingrese el D.N.I. de un cliente a buscar\n");
    scanf("%i", &buscar);
    while(fread(&clientes,sizeof(Cliente),1,archi)>0)
    {
        if(buscar==clientes.dni)
        {
            posicion=ftell(archi)/sizeof(Cliente);
        }
    }
}
  return posicion;
}

void bajaCliente()                 
{
  Cliente clienteBaja;
  int posicion;
  FILE*archi=fopen("cliente","r+b");
  posicion=buscaCliente(archi);
  if(posicion==(-1))
{
    printf("El cliente no existe");
}
  else
{
    fseek(archi,(posicion-1)*(sizeof(Cliente)),SEEK_SET);
    clienteBaja.baja='s';
    fseek(archi,sizeof(Cliente),SEEK_CUR);
}    
  fwrite(&clienteBaja,sizeof(Cliente),1,archi);
  fclose(archi);
}
    
asked by ShanGhai 20.06.2018 в 01:27
source

1 answer

0

I would say that your problem is that the client that you are modifying in low is clienteBaja , which you have created within the method without initializing its "attributes", so that these contain "random" values. Therefore, I would recommend that you read with fread the entire position of the client that you want to modify low and save your content in clienteBaja to have the original attributes before changing low. You could do this by passing buscaCliente() a pointer to cliente to save the client found in its content and then pass that client to low, ie:

int buscaCliente(FILE*archi,Cliente* c )
{
  Cliente clientes;
  int buscar=0;
  int  posicion=-1;
  if(archi!=NULL)
{
    printf("Ingrese el D.N.I. de un cliente a buscar\n");
    scanf("%i", &buscar);
    while(fread(&clientes,sizeof(Cliente),1,archi)>0)
    {
        if(buscar==clientes.dni)
        {
            posicion=ftell(archi)/sizeof(Cliente);
            *c = clientes;
        }
    }
}
  return posicion;
}


void bajaCliente(Cliente c)                 
{
  Cliente clienteBaja = c;

  int posicion;
  FILE*archi=fopen("cliente","r+b");
  posicion=buscaCliente(archi);
  if(posicion==(-1))
{
    printf("El cliente no existe");
}
  else
{
    fseek(archi,(posicion-1)*(sizeof(Cliente)),SEEK_SET);
    clienteBaja.baja='s';
    fseek(archi,sizeof(Cliente),SEEK_CUR);
    fwrite(&clienteBaja,sizeof(Cliente),1,archi);
}    

  fclose(archi);
}

Also, I would put the fwrite inside the else, because if I have understood correctly what you intend to do, you do not want to write a new client, but modify the data of one in case there is

    
answered by 24.07.2018 в 13:49