I'm writing some code to serialize some data and write the serialize data to a file on disk. Currently data is in void* buffer and then trying to serialize using tpl with TPL_MEM so that later it can be write to file. But I am not very sure that how to get this serialize data to file.Is TPL the best and optimum way to do this ? troydhanson.github.io/tpl/index.html

Is there a reason you want to use that library instead of just standard C FILE* functions? If all you want to do is write it to a file then just standard C library fwrite(), then fread() to read it back. You won't get more efficient then that. But if you want something more complex such as memory mapped files then maybe that library will do. Just scanning over the contents of the header file the library looks to be much more than what you need.

I will use fwrite() and fread() functions when I will do file operations but before that I just want my data is serialize properly.I need to do the serialization of data as I the data is in structural format and it need to be stored in file in binary format on disk, which can later be used .As C doesnt provide direct serialization I need to use the lib.

As C doesnt provide direct serialization

Serialization is nothing more than a fancy word for read/write to a file stream, whether the stream is the console screen, a file system, serial port, internet connection or something else. In your case "serialize" just simply means read/write to a file in the hard drive.

C langusge supports both binary and text files, you choose the file type in the second parameter to fopen(). "wb" means "write binary" while "w" or "wt" means "write text". The same with reading -- "rb" is "Read binary" and "rt" or "r" means "read text"

If you have a structure and you want to write it in binary mode then just do something like this:

#include <stdio.h>

struct foo
{
   int x,y,z;
   char something[255];
}



int main()
{
   struct foo fooArray[8];
   // open the file for binary writing
   FILE* fp = fopen("filename.bin","wb");
   if( fp != NULL)
   {
       // write out the entire array in binary
       fwrite(fp, fooArray,sizeof(fooArray));
       fclose(fp);
    }

    // now read it back
   fp = fopen("filename.bin","rb");
   if( fp != NULL)
   {
       // write out the entire array in binary
       fread(fp, fooArray,sizeof(fooArray));
       fclose(fp);
    }


}

You apparently just have a void* so you will have to typecast it to char* in the fread() and fwrite() functions. The last parameter to those functions are the number of bytes to read/write, so I hope you have that info too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.