我無法理解爲什麼我的代碼不能按預期工作,我確信它與我對fread和fwrite的理解有關。使用fread&fwrite,與二進制相關
這是我的代碼的片段,原諒格式和懶惰的風格。
typedef struct record_t{
char name[20];
unsigned int id;
char toy[30];
}record_t;
int main(int argc, char** argv){
FILE *readFile, *writeFile;
record_t *recordPtr;
int i;
if((recordPtr = malloc(sizeof(struct record_t))) == NULL)
{
perror("Error allocating record space\n");
exit(EXIT_FAILURE);
}
strcpy(recordPtr->name, "Michael");
recordPtr->id = 3;
strcpy(recordPtr->toy, "Hello Kitty");
printf("Writing %s - %d - %d - %d - %s\n", recordPtr->name,
recordPtr->id, recordPtr->toy);
if((writeFile = fopen("test.bin", "wb")) == NULL)
{
perror("Error opening writing file\n");
exit(EXIT_FAILURE);
}
for(i = 0; i < 2; ++i){
recordPtr->id = i ;
fwrite(&recordPtr, sizeof(struct record_t), 1, writeFile);
printf("%s - %d - %s, ", recordPtr->name, recordPtr->id, recordPtr->toy);
printf("Record Written.\n");
}
fclose(writeFile);
recordPtr = NULL;
if((readFile = fopen("test.bin", "rb")) == NULL)
{
perror("Error opening reading file\n");
}
exit(EXIT_FAILURE);
recordPtr = NULL;
for(i=0; i < 2; ++i){
fread(&recordPtr, sizeof(struct record_t), 1, readFile);
printf("%s - %d - %s, Read back.\n" recordPtr->name, recordPtr->id, recordPtr->toy);
}
fclose(readFile);
exit(EXIT_SUCCESS);
}
代碼的想法只是記錄一下,寫入二進制文件,然後從二進制文件中讀回來。 我的問題是隻有最後一個條目被讀回,所以我確定我對fread的理解有問題。
提前感謝您。
你是說當它通過讀取循環時,它會全部三次打印id 2,而不是0,1,2? – Barmar
我認爲問題在於正在寫入的記錄是同一條記錄,一遍又一遍。所以而不是看到記錄0然後1然後2等我看到最後一個記錄寫1,然後1,然後1. – husked
你讀過20分鐘前發佈的答案嗎? – Barmar