Write a file pointer in C

I have a structure:

typedef struct student {
  char *name;
  char *surname;
  int age;
} Student;

I need to write a structure to a binary file.
Here is my attempt:

Student *s = malloc(sizeof(*s));

I fill my structure with data, and then write the structure to a file with:

fwrite(s, sizeof(*s), 1, fp);

There is no first name or last name in my file. Instead, they have a corresponding pointer address char *.
How can I write char *to a file instead of a pointer address?

+6
source share
7 answers

You need to dereference your pointer and write particles to the structure. (You should not directly refer to the structure, but rather encode parts of it and write them:

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); 
+11
source

, , - , .

- :

typedef struct
{
    char name[MAX_NAME_LEN];
    char surname[MAX_SURNAME_LEN];
    int age;
} Student;
+4

, , , .

typedef structure student { char name[100]; char surname[100]; int age; } 

else .

+3

C ( ) . , , , , endianness endianness.

( ), / :

size_t length;

length = strlen(s->name) + 1;
fwrite(&length, sizeof(length), 1, fp);
fwrite(s->name, 1, length, fp);

length = strlen(s->surname) + 1;
fwrite(&length, sizeof(length), 1, fp);
fwrite(s->surname, 1, length, fp);

fwrite(&s->age, sizeof(s->age), 1, fp);

unserialize:

size_t length;

fread(&length, sizeof(length), 1, fp);
s->name = malloc(length);
fread(s->name, 1, length, fp);

fread(&length, sizeof(length), 1, fp);
s->surname = malloc(length);
fread(s->surname, 1, length, fp);

fread(&s->age, sizeof(s->age), 1, fp);

, , . , , int s, size_t .., , / , .

, tpl, C.

+3

s , :

size_t nameCount = strlen(s->name) + 1;
fwrite(s->name, sizeof(char), nameCount, fp);

size_t surnameCount = strlen(s->surname) + 1;
fwrite(s->surname, sizeof(char), surnameCount, fp);
0

, "" , . "b" mode fopen (r +\w\a .. rb +\wb\ab).

, fread ( "rb" , .

0

, . , , , , .

size_t len;
len = strlen(s->name)+1;
fwrite(&len,sizeof(len),1,stream);
fwrite(s->name,sizeof(*(s->name)),len,stream);
...

-

Student * s = malloc(sizeof(*s));
size_t len;
fread(&len,sizeof(len),1,stream);
s->name = malloc(len);
fread(s->name,sizeof(*(s->name)),len,stream);
...
0

All Articles