Search code examples
cfilerandom-access

Update a file record


I'm trying to update a record of a random access file in C. I just need to update the integer cant_discos in every record of my .dat file.

This is the code i wrote, i have 2 problems:

1) My code just let me edit the first record of my file.

2) The program doesn't update the record.

typedef struct{
int codigo;
char nombre[30];
char integrantes[100];
int cant_discos;
} t_bandas;

int main()
{
   int res,cant;
t_bandas aux;
    FILE * fd;
    fd=fopen("bandas.dat","rb+");
    if(fd==NULL){ puts("ERROR"); exit(-1)}

while(!feof(fd)){
res=fread(&aux,sizeof( t_bandas),1,fd);
if(res!=0){
printf("New cant value..\n");
scanf("%d",&cant);
aux.cant_discos=cant;
fwrite(&aux,sizeof( t_bandas),1,fd);    
}    
}
fclose(fd);
    return 0;    }

Solution

  • fseek should be called when switching between read and write.

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct{
        int codigo;
        char nombre[30];
        char integrantes[100];
        int cant_discos;
    } t_bandas;
    
    int main()
    {
        int res,cant;
        long pos = 0;
        t_bandas aux;
        FILE * fd;
    
        fd=fopen("bandas.dat","rb+");
        if(fd==NULL){
            puts("ERROR");
            exit(-1);
        }
    
        while ( ( res = fread ( &aux, 1, sizeof ( t_bandas), fd)) == sizeof ( t_bandas)) {
            printf("New cant value..\n");
            scanf("%d",&cant);
            aux.cant_discos=cant;
            fseek ( fd, pos, SEEK_SET);//seek to start of record
            fwrite(&aux,sizeof( t_bandas),1,fd);
            pos = ftell ( fd);//store end of record
            fseek ( fd, 0, SEEK_CUR);//seek in-place to change from write to read
        }
        fclose(fd);
        return 0;
    }