2016-02-17 46 views
1

我試圖更新C中的一個隨機訪問文件的記錄。我只需要更新我的.dat文件的每個記錄中的整數cant_discos。更新文件記錄

這是我寫的代碼,我有2個問題:

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

發佈代碼時,一致的可讀縮進將使您的問題更具可讀性。在發佈代碼之前檢查預覽(如果看起來不太好,則在之後編輯)。 – crashmstr

回答

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

我不是一個代碼的一部分: fseek(fd,0,SEEK_CUR); 這是否將流設置爲文件的第一位?爲什麼我需要這個? @ user3121023 –

+1

剛剛在這裏找到了我的答案: http://stackoverflow.com/questions/1713819/why-fseek-or-fflush-is-always-required-between-reading-and-writing-in-the-read- w ^ –