Archived

This topic is now archived and is closed to further replies.

programering

How to load/store classes data in filebuffers?

Recommended Posts

//Ok You want to Store a Struct in a File and Load it ...
//See this
//Suppose

#include <fstream.h>
struct MyStruct{
int x;
float y;
char t;
};

//For Saving into File ...
MyStruct mystruct;
//Fill my Struct with data here ...
//*********************************
ofstream ofs("File.txt");
ofs.write((char*)&mystruct,sizeof(mystruct));

//For Loading
ifstream ifs("File.txt");
ifs.read((char*)&mystruct,sizeof(mystruct));
//*********************************
That is all

Come to visit Egypt (the Land of Civilization)

Share this post


Link to post
Share on other sites
First, you must use <fstream> and not <fstream.h>.
Second, you may only serialize that way classes that have no virtual functions, no pointer, reference or object members. These are known as POD (plain old data) classes.

The proper way to save an object is to define a function that explicitely save and load the relevant data members. Do not indiscriminately use bitwise copying.





[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share this post


Link to post
Share on other sites