C++序列化工程文件时的相关知识点

1、文件的写入与读取;

	ifstream input("test.svl", ios::in | ios::binary);
	int nLength;
	string strTemp;
	input.read((char*)&nLength, sizeof(int));
	strTemp.resize(nLength);
	input.read((char*)&strTemp[0], nLength);
	std::cout << strTemp;

	ofstream output("test.svl", ios::out | ios::binary);
	string strTemp = "Hello,world!";
	int length = strTemp.size();
	output.write((char*)&length, sizeof(int));
	output.write(strTemp.c_str(), strTemp.size());
	output.close();

2、OpenCV中的Mat图片的序列化转换,可通过base64编码实现。Mat转base64后续实现,可通过该链接转换;

static inline bool is_base64(unsigned char c) {

	return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_decode(std::string const& encoded_string)
{
	static const std::string base64_chars =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"abcdefghijklmnopqrstuvwxyz"
		"0123456789+/";
	int in_len = encoded_string.size();
	int i = 0;
	int j = 0;
	int in_ = 0;
	unsigned char char_array_4[4], char_array_3[3];
	std::string ret;
	while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) 
	{
		char_array_4[i++] = encoded_string[in_]; in_++;
		if (i == 4) 
		{
			for (i = 0; i < 4; i++) 
			{
				char_array_4[i] = base64_chars.find(char_array_4[i]);
			}
			char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
			char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
			char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
			for (i = 0; (i < 3); i++) 
			{
				ret += char_array_3[i];
			}
			i = 0;
		}
	}
	if (i) 
	{
		for (j = i; j < 4; j++) 
		{

			char_array_4[j] = 0;
		}
		for (j = 0; j < 4; j++) 
		{

			char_array_4[j] = base64_chars.find(char_array_4[j]);
		}
		char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
		char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
		char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
		for (j = 0; (j < i - 1); j++)
		{

			ret += char_array_3[j];
		}
	}
	return ret;
}

Mat str2mat(const std::string& s) 
{

	std::string decoded_string = base64_decode(s);
	std::vector<uchar> data(decoded_string.begin(), decoded_string.end());
	cv::Mat img = imdecode(data, IMREAD_UNCHANGED);
	return img;
}

 

Guess you like

Origin blog.csdn.net/Stone_Wang_MZ/article/details/108264493