1

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;    }
Marco_D
  • 85
  • 1
  • 2
  • 6
  • When posting code, a consistent readable indentation will make your question more readable. Check the preview before posting code (and edit afterwards if it does not look good). – crashmstr Feb 17 '16 at 13:26

1 Answers1

1

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;
}
user3121023
  • 8,181
  • 5
  • 18
  • 16
  • I'm not undestarding a part of the code: fseek ( fd, 0, SEEK_CUR); Do this set the stream to the first bit of the file? Why i need this? @user3121023 – Marco_D Feb 17 '16 at 18:47
  • 1
    just found my answer here: http://stackoverflow.com/questions/1713819/why-fseek-or-fflush-is-always-required-between-reading-and-writing-in-the-read-w – Marco_D Feb 17 '16 at 19:13