Some fwrite question

Programming, for all ages and all languages.
Post Reply
NOTNULL

Some fwrite question

Post by NOTNULL »

Hello all,
Consider the structure.

Code: Select all

struct recs   {
    int no;
    char *name;
}r;
Assume that i have allocated memory for the variable r.name and copied some data. So, while writing the structure to a file using fwrite, the 4 byte address of the name will only be stored in the file. Is there any other way to store the content of the data pointed to by the name pointer through the fwrite call?

Any help greatly appreciated.
zloba

Re:Some fwrite question

Post by zloba »

you can't fwrite the whole thing at once, but you can make a function or a method that does that piece by piece.

Code: Select all

// error checking omitted due to laziness

// C++: tell it to write itself :)
struct recs{
  int no;
  char *name;

  void fwrite(FILE * f){
   ::fwrite(&no,sizeof(no),1,f);
   ::fwrite(name,strlen(name)+1,1,f);
   // assuming you want to write the terminating zero as well
  }
};

// or, if you're doing Plain C :-\
void recs_fwrite(recs * p, FILE * f){
   fwrite(&p->no,sizeof(p->no),1,f);
   fwrite(p->name,strlen(p->name)+1,1,f);
   // assuming you want to write the terminating zero as well
}
// since you'll end up with variable-length records, you'll have to worry about how your records are delimited in the file, whether you need to write the zero or length or whatever
Post Reply