这是一个简单的示例程序,它将对象写入文件并读取它。
//Objfile.h
#include<iostream>
#include<fstream>
#include<string.h>
#define STRLEN 10
class A
{
public:
int a;
float c;
char *f;
A():a(10),c(30.5){
f=new char[STRLEN];
memset(f, '\0', STRLEN);
strcpy(f,"fed");
std::cout<<"\n A";
}
~A() { delete[] f; }
void print() { std::cout<<" a:"<<a<<" g:"<<g<<" f:"<<f; }
};
//ObjFile.cpp // Writes Object to the file
#include<objfile.h>
main()
{
std::ofstream out("obj.txt", std::ios::out|std::ios::binary);
if (!out) {
std::cout<<"\n Error in opening output file out.txt";
return 0;
}
A a;
out.write((char*)&a, sizeof(a));
out.close();
}
//ObjfileRead.cpp //Reads record (Object) from the file and prints
#include<objfile.h>
main()
{
std::ifstream in("obj.txt", std::ios::in|std::ios::binary);
if (!in) {
std::cout<<"in file can't open \" obj.txt \" ";
return 0;
}
A *b;
char *temp_obj=new char[sizeof(A)];
in.read(temp_obj,sizeof(A));
b=reinterpret_cast<A*>(temp_obj);
b->print();
in.close();
return 0;
}