Search code examples
cbinaryfwritefread

Using fread & fwrite, in relation to binary


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.


Solution

  • 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.