我无法理解为什么我的代码不能按预期工作,我确信它与我对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