Home > database >  How do I write a whole struct to a TEXT file with fwrite(), using structure pointers while the struc
How do I write a whole struct to a TEXT file with fwrite(), using structure pointers while the struc

Time:01-15

So I have a structure pointer named Cars leads to a struct which contains some char pointers that have text in them. And I am trying to write the whole structure into a text file using fwrite.

I have used calloc to allocate memory for the structures before trying to put text into the char * from the struct. Everything works fine, I can print any of the values of the struct. But I can't get them out to the text file. After I call fwrite, all I get in the text file is random text. I thought it would be trying to write stuff out in binary, but it's not that. Also, everytime the output slightly changes, it feels like it is returning some random adresses. Here is my code:

int numberOfCars;

typedef struct
{
    char *plate;
    char *model;
    char *color;
    char *ownerName;
    char *problems;
    char *status;
    int year;

} car ;
void writeIntoDatabase(car *);
int main()
{
    car *Cars;
    numberOfCars=2;
    Cars=(car *)calloc(numberOfCars, sizeof(car));

    int i=0;
    (Cars i)->plate="CJ23YOU";
    (Cars i)->model="Mazda";
    (Cars i)->color="Black";
    (Cars i)->ownerName="Makro_And";
    (Cars i)->problems="Rattling_noise";
    (Cars i)->status="Fixed";
    (Cars i)->year=2019;
    i  ;
    (Cars i)->plate="CJ65YOM";
    (Cars i)->model="Volkswagen";
    (Cars i)->color="White";
    (Cars i)->ownerName="Mars Andy";
    (Cars i)->problems="Rattling noise lllas";
    (Cars i)->status="Pending";
    (Cars i)->year=2009;

    writeIntoDatabase(Cars);
   // fprintf(DB_ptr,"%s",(Cars i)->plate);
    printf("%s", (Cars i)->plate);
    return 0;
}

void writeIntoDatabase(car *Cars)
{
    FILE *DB_ptr=fopen("carsDBwrite.txt","w");
    fwrite(Cars,sizeof(car),numberOfCars,DB_ptr);
    fclose(DB_ptr);
}

The output in my file is: dP@ lP@ rP@ xP@ ‚P@ ‘P@ ã —P@ ŸP@ ªP@ °P@ ºP@ ÏP@ Ù

I would be really grateful for any suggestions and/or fixes, or any other way of making this work. I'm guessing fprint f would be one, but I didnt really want to use that as fwrite seemed as it would do the task better. Thank you in advance!

CodePudding user response:

The reason it is not working is that fwrite write one continuous block of bytes to a file, however your struct contains pointers pointing elsewhere so what you are storing is basically the addresses of the strings instead of the strings themselves.

If you want to use fwrite you need to make the struct a continuous block of bytes, i.e. use char [] in your struct with fixed sizes.

E.g.

typedef struct
{
    char plate[MAXSIZE];
    char model[MAXSIZE];
    char color[MAXSIZE];
    char ownerName[MAXSIZE];
    char problems[MAXSIZE];
    char status[MAXSIZE];
    int year;

} car ;

CodePudding user response:

The function fwrite is generally used for writing to binary files, not text files.

Also, writing the values of the pointers to the file is not what you want. You want to write the strings to which the pointers point, not the values of the pointers themselves.

The function that you need is the function fprintf. That function allows you to pass a pointer to a string and to print the actual string, instead of the value of the pointer.

Here is an example program based on your posted code, with a few miscellaneous improvements:

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

typedef struct
{
    char *plate;
    char *model;
    char *color;
    char *ownerName;
    char *problems;
    char *status;
    int year;

} car;

void writeIntoDatabase( car *cars, int num_cars );

int main( void )
{
    car cars[] = {
        {
            "CJ23YOU",
            "Mazda",
            "Black",
            "Makro_And",
            "Rattling_noise",
            "Fixed",
            2019
        },
        {
            "CJ65YOM",
            "Volkswagen",
            "White",
            "Mars Andy",
            "Rattling noise lllas",
            "Pending",
            2009
        }
    };

    writeIntoDatabase( cars, sizeof cars / sizeof *cars );

    return 0;
}

void writeIntoDatabase( car *cars, int num_cars )
{
    FILE *DB_ptr = fopen( "carsDBwrite.txt", "w" );
    if ( DB_ptr == NULL )
    {
        fprintf( stderr, "Error opening file!\n" );
        exit( EXIT_FAILURE );
    }

    //print one car per loop iteration
    for ( int i = 0; i < num_cars; i   )
    {
        fprintf(
            DB_ptr,
            "%s\n%s\n%s\n%s\n%s\n%s\n%d\n",
            cars[i].plate,
            cars[i].model,
            cars[i].color,
            cars[i].ownerName,
            cars[i].problems,
            cars[i].status,
            cars[i].year
        );
    }

    fclose(DB_ptr);
}

This program writes the following to the output file:

CJ23YOU
Mazda
Black
Makro_And
Rattling_noise
Fixed
2019
CJ65YOM
Volkswagen
White
Mars Andy
Rattling noise lllas
Pending
2009
  • Related