更新文件记录

时间:2016-02-17 04:17:24

标签: c file random-access

我正在尝试更新C中随机访问文件的记录。我只需要在.dat文件的每个记录中更新整数cant_discos。

这是我写的代码,我有两个问题:

1)我的代码只是让我编辑我文件的第一条记录。

2)程序不更新记录。

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;    }

1 个答案:

答案 0 :(得分:1)

在读写之间切换时应该调用

fseek

#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;
}