程序能正常输出,直到最后退出程序的时候报错。
代码如下:
//************//binary_serialization.h
namespace binary_space {
template<class T>
extern bool serialize(T& n0, const char filename[]);
template<class T>
extern bool deserialize(T& n1, const char filename[]);
}
//************//binary_serialization.cpp
#include "binary_serialization.h"
#include <fstream>
using namespace binary_space;
template<class T>
bool binary_space::serialize(T& n0, const char filename[]) {
FILE *fp = fopen(filename, "rb+");
if (!fp)
{
fp = fopen(filename, "w");
if (!fp) {
std::cout << "Can not open the file named " << filename << std::endl;
return false;
}
}
fwrite(&n0, sizeof(n0), 1, fp);
fclose(fp);
return true;
}
template<class T>
bool binary_space::deserialize(T& n1, const char filename[]) {
FILE *fp = fopen(filename, "rb+");
if (!fp)
{
std::cout << "Can not open the file named " << filename << std::endl;
return false;
}
fread(&n1, sizeof(n1), 1, fp);
fclose(fp);
return true;
}
//************//Main.cpp
struct vector_test{
std::vector<int > myint;
};
int main(){
vector_test my_vector;
//结构vector_test 里面包含一个vector,下面为赋值
my_vector.myint.push_back(0);
my_vector.myint.push_back(1);
my_vector.myint.push_back(2);
bool check_s=binary_space::serialize(my_vector, "vector.txt");
//将一个结构写入一个文件
if (check_s == false) {
return 0;
}
vector_test my_vector2;
binary_space::deserialize(my_vector2, "vector.txt");
//从文件中读取这个类,实现在.cpp里面
//以下为输出
std::cout << my_vector2.myint[0] << std::endl;
std::cout << my_vector2.myint[1] << std::endl;
std::cout << my_vector2.myint[2] << std::endl;
//test vector end
}
问题是,能正确输出0,1,2但是程序结束,就报错。
可能是内存泄漏的问题,不确定自己写的对不对。