Mind Ocean
Mind Ocean

Reputation: 3

Trying to print a dynamic array of structs from a file

So basically, I'm trying to write a program that:

  1. reads a dynamic array of structs of an unknown size;
  2. writes it into file;
  3. prints it on the screen.

All of that while using different functions and a dynamic array of struct. This is the code I'm working on; the printing function is not working correctly, it appears that the data gets lost in the midst of all the operations :/ can someone please show me how to fix this?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILE_CARS "cars.txt"

typedef struct car 
{
    long int id;
    char name[100];
}Car;

void reading(Car *vec){

    printf("ID: ");
    scanf("%d", &vec->id);
    printf("Name: ");
    scanf(" %[^\n]", vec->name);

    FILE *fab = fopen(FILE_CARS, "ab+");
    fwrite(&vec, sizeof(Car), 1, fab);
    fclose(fab);
}

void printing(Car *vec){

    //vec = (Car*) malloc(sizeof(Car));

    FILE *fr = fopen(FILE_CARS, "rb");

    while(fread(vec, sizeof(Car), 1, fr)){
        printf("\nID: %d\n", vec->id);
        printf("Name: %s\n", vec->name);
    }

    fclose(fr);
}


int main(){
    int op;

    Car *vec = (Car*) malloc (sizeof(Car));
    
    do{
        scanf("%d", &op);

        switch(op){
            case 1:
                reading(vec);
                break;
            case 2:
                printing(vec);
                break;
            case 3:
                printf("End of program");
                break;
            default:
                printf("invalid option");
        }

    }while(op != 3);
}

Upvotes: 0

Views: 29

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

In the line

fwrite(&vec, sizeof(Car), 1, fab);

You are writing the pointer, which will be useless, to the file. This is also dangerous because sizeof(Car) is typically larger than pointers and out-of-bound read will occur.

Use this line without & instead:

fwrite(vec, sizeof(Car), 1, fab);

Upvotes: 1

Related Questions