Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write a structure to a file 2

Status
Not open for further replies.

Wings

Programmer
Feb 14, 2002
247
0
0
US
Hello,
I want to write a structure to a text file, the issue is though that it could be one of several structures. Instead of creating a function to write each variable in the structure to a file,and a seperate function for each structure type, is it possible to simply pass an entire structure into the file? If so, how?

Thanks for the help
 
Try something like this:

Code:
struct struct1
{
   int iNum;
   float fNum;
};

struct struct2
{
   double dNum;
   char szName[20];
};

struct1 s1 = { -2, 3.14 };
struct2 s2 = { 7.8675, "Bob" };
ofstream fileOut( "/tmp/filename.txt" );
fileOut.open();
fileOut << static_cast<const char*>(s1);
fileOut << static_cast<const char*>(s2);
fileOut.close();

Note: unless your structs are the same size or have something to distinguish them, you'll have a hard time reading them back in properly.
 
You should also be aware that most compilers will introduce padding bytes between some structure fields, for word alignment. You can eliminate the padding by setting the compiler to pack on byte boundaries. In VC++ you can do this:

Code:
#pragma pack(1)

Also, the same program compiled on a little-endian machine and a big-endian machine will produce different output (integers will be byte-swapped).
 
If you dont mind adding extra data to a struct you could do

struct structOne
{
size_t structSize;
// other data

structOne():structSize(sizeof(*this)){}
};

struct structTwo
{
size_t structSize;
// other data (different of course)

structTwo():structSize(sizeof(*this)){}
};

etc...

when you read it in, read the first 4 bytes for the size, then read in the rest. You can make it easier by setting struct size to sizeof(*this)-sizeof(structSize)

Matt



 
Is it simpler?
Code:
struct S1 
{
...
};
struct S2
{
...
};
fstream f;
S1 s1;
S2 s2;
...
f.write((char*)&s1,sizeof s1);
f.write((char*)&s2,sizeof s2);
...
f.read((char*)&s1,sizeof s1);
f.read((char*)&s2,sizeof s2);
...
It's a very unsafety code, but it's so simple (in spirit of the good old C;)...
True solution is to implement correct and robust rollin/rollout members for every structures...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top