1 #include<stdio.h> 2 #include<iostream> 3 #include<fcntl.h> 4 #include<sys/types.h> 5 #include<sys/stat.h> 6 #include<vector> 7 #include <unistd.h> 8 using namespace std; 9 10 class A 11 { 12 private: 13 int i; 14 public: 15 A(){ 16 i = 0; 17 } 18 explicit A(int j){ 19 i = j; 20 } 21 virtual ~A(){ 22 23 } 24 public: 25 void f(){ 26 cout<<"in f() "<<i<<endl; 27 } 28 public: 29 bool Serialize(const char* pFilePath){//序列化 30 int fd = open(pFilePath,O_RDWR | O_CREAT | O_TRUNC, 0);//打开文件,如果文件不存在,就创建文件 31 cout << "begin Serialize"<< endl;//给个提示 32 if(fd == -1){//如果说打开文件或者创建文件错误,返回错误 33 cout << "Serialize open error" << endl; 34 return false; 35 } 36 if (write(fd,&i,sizeof(int)) == -1)//如果说向文件里面写入数据时出错,出错原因有磁盘满,没有访问权限,超过了给定进程的文件长度等 37 { 38 cout << "Serialize write error" << endl; 39 close(fd);//关闭文件 40 return false;//返回错误 41 } 42 cout << "Serialize finish" << endl; 43 return true;//如果上述打开与写都没有错误,那么则序列化成功 44 } 45 bool Deserialize(const char* pFilePath){//反序列化 46 int fd = open(pFilePath,O_RDWR);//用读写的方式打开文件 47 cout << "Deserialize begin" << endl; 48 if (fd == -1)//打开文件错误 49 { 50 cout <<"Deserialize open error"<<endl; 51 return false;//返回错误 52 } 53 int r = read(fd,&i,sizeof(int));//从序列化的文件读出数据 54 if (r == -1)//读文件出错 55 { 56 cout << "Deserialize read error"; 57 close(fd);//关闭文件 58 return false;//返回错误 59 } 60 if (close(fd) == -1){//如果关闭文件错误 61 cout << "Deserialize close error" << endl; 62 return false;//返回错误 63 } 64 cout << "Deserialize finish" << endl; 65 return true;//上述操作都成功,那么则反序列化成功 66 } 67 bool Serialize(int fd) const 68 { 69 if(-1==fd) 70 return false; 71 72 if(write(fd,&i,sizeof(int))==-1) 73 return false; 74 75 return true; 76 } 77 bool Deserialize(int fd) 78 { 79 if(-1==fd) 80 return false; 81 82 int r=read(fd,&i,sizeof(int)); 83 if((0==r)||(-1==r)) 84 return false; 85 86 return true; 87 } 88 }; 89 class SerializerForAs 90 { 91 public: 92 SerializerForAs() 93 {} 94 virtual ~SerializerForAs() 95 { 96 } 97 98 public: 99 bool Serialize(const char *pFilePath, const std::vector<A>& v) 100 { 101 int fd = open(pFilePath,O_RDWR | O_CREAT | O_TRUNC, 0); 102 if(-1==fd) 103 return false; 104 105 for(int i=0;i<v.size();i++) 106 { 107 v[i].Serialize(fd); 108 } 109 close(fd); 110 return true; 111 } 112 bool Deserialize(const char *pFilePath, std::vector<A>& v) 113 { 114 int fd=open(pFilePath,O_RDWR); 115 if(-1==fd) 116 return false; 117 118 for(;;) 119 { 120 A a; 121 if(a.Deserialize(fd)==true) 122 { 123 v.push_back(a); 124 } 125 else 126 break; 127 } 128 129 close(fd); 130 131 return true; 132 } 133 }; 134 int main() 135 { 136 137 A a1(1),a2(2),a3(3); 138 139 std::vector<A> v; 140 v.push_back(a1); 141 v.push_back(a2); 142 v.push_back(a3); 143 144 SerializerForAs s; 145 s.Serialize("data1.txt",v); 146 s.Deserialize("a1.txt",v); 147 for(int i=0;i<3;i++) 148 { 149 v[i].f(); 150 } 151 152 return 0; 153 }
原文:https://www.cnblogs.com/xmthh/p/14764252.html