I have a structure:
typedef struct student {
char *name;
char *surname;
int age;
} Student;
I need to write the structure into a binary file.
Here is my attempt :
Student *s = malloc(sizeof(*s));
I fill my structure with data and then I write the struct into the file with :
fwrite(s, sizeof(*s), 1, fp);
In my file, name and surname don't exist. Instead they have their respective address of their char *
pointer.
How can I write a char *
into a file instead of the address of the pointer ?
FILE *fp; To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.
A file pointer stores the current position of a read or write within a file. All operations within the file are made with reference to the pointer. The data type of this pointer is defined in stdio. h and is named FILE.
General Syntax:*fp = FILE *fopen(const char *filename, const char *mode); Here, *fp is the FILE pointer ( FILE *fp ), which will hold the reference to the opened(or created) file. filename is the name of the file to be opened and mode specifies the purpose of opening the file.
You need to dereference your pointer and write the parts of the struct. (You should not fwrite a struct directly, but rather encode its parts and write those:
Student *s = malloc(sizeof(*s));
s->name = "Jon";
s->surname = "Skeet";
s->age = 34;
// ....
fwrite(s->name, sizeof(char), strlen(s->name) + 1, fp);
fwrite(s->surname, sizeof(char), strlen(s->surname) + 1, fp);
//This one is a bit dangerous, but you get the idea.
fwrite(&(s->age), sizeof(s->age), 1, fp);
You will have to do some extra work to write out the data pointed to by the structure elements - probably just write it out element by element.
Alternatively change your structure to something like this:
typedef struct
{
char name[MAX_NAME_LEN];
char surname[MAX_SURNAME_LEN];
int age;
} Student;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With