Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write pointer to file in C

Tags:

c

file

pointers

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 ?

like image 472
Sergey Avatar asked May 04 '10 07:05

Sergey


People also ask

What is file * fp in C?

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.

What is a file pointer in C?

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.

What is file pointer syntax?

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.


2 Answers

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); 
like image 119
Williham Totland Avatar answered Sep 30 '22 08:09

Williham Totland


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;
like image 34
Paul R Avatar answered Sep 30 '22 08:09

Paul R