我很难理解为什么我的代码没有按预期工作,我确信这与我对 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 的理解有问题。
先感谢您。