Reputation: 3
I'm having trouble getting to understand why my code is not working as intended, and I'm sure it has to do with my understanding of fread and fwrite.
Here is a snippet of my code, excuse the formatting and lazy style.
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);
}
The idea of the code is just to take a record, write it to binary, then read it back from binary. My issue is that only the last entry is read back, so I'm sure I have a problem with my understanding of fread.
Thank-you in advance.
Upvotes: 0
Views: 1553
Reputation: 455380
fwrite(&recordPtr, sizeof(struct record_t), 1, writeFile);
fread(&recordPtr, sizeof(struct record_t), 1, readFile);
should be:
fwrite(recordPtr, sizeof(struct record_t), 1, writeFile);
fread(recordPtr, sizeof(struct record_t), 1, readFile);
Next:
if( (readFile = fopen("test.bin", "rb")) == NULL)
{
perror("Error opening reading file\n");
}
exit(EXIT_FAILURE);
Should be
if( (readFile = fopen("test.bin", "rb")) == NULL)
{
perror("Error opening reading file\n");
exit(EXIT_FAILURE);
}
And
when you are reading the structure back, the buffer is pointing to NULL!!!
So make sure you allocate memory and make recordPtr
point to it before you use recordPtr
in fread
.
Upvotes: 1
Reputation: 62106
This
fwrite(&recordPtr, sizeof(struct record_t), 1, writeFile);
isn't writing the structure to the file, it's attempting to write the pointer recordPtr
to it followed by whatever follows it in memory.
Likewise this
fread(&recordPtr, sizeof(struct record_t), 1, readFile);
isn't reading the structure into the memory you've allocated for it, it's attempting to overwrite the pointer recordPtr
and whatever follows it in memory with file data.
You need to drop that ampersand.
Upvotes: 1