kv文件读写 in Python & C++
2015-01-04 11:26
441 查看
文件格式均为kv对,即keylength, key, valuelen, value. 如何对其进行读写操作,本文列出demo code。感谢涛哥贡献部分代码,这里分享,方便大家使用。
Python:
C++:
如果value是一张图片的data,调用的时候可以用opencv的imdecode直接进行转换,生成cv::Mat类型的图片
Python:
def readimg(): fr = open('IMG_2963.JPG','r') keylen = struct.unpack('i',fr.read(4))[0] key = fr.read(keylen) valuelen = struct.unpack('i',fr.read(4))[0] value = fr.read(valuelen) fr.close() def writeimg(): fw = open('Img_to_Write','w') key = 'key' fw.write(struct.pack('i',len(key))) fw.write(key) fw.write(struct.pack('i',len(val))) fw.write(val) fw.close()
C++:
inline bool readkv(istream &ifs,string &key,string &value) { int keylen; ifs.read((char*)&keylen,4); if (!ifs) { return false; } key.resize(keylen); ifs.read((char*)key.c_str(),keylen); int valuelen; ifs.read((char*)&valuelen,4); value.resize(valuelen); ifs.read((char*)value.c_str(),valuelen); return true; } inline void writekv(ostream &ofs,const string & key,const string & value) { unsigned int klen = key.size(); unsigned int vlen = value.size(); ofs.write((const char*)&klen,4); ofs.write(key.c_str(),klen); ofs.write((const char*)&vlen,4); ofs.write(value.c_str(),vlen); ofs.flush(); }
如果value是一张图片的data,调用的时候可以用opencv的imdecode直接进行转换,生成cv::Mat类型的图片
cv::Mat buf(1,value.size(),CV_8U,(void *)value.c_str()); cv::Mat srcmat = cv::imdecode(buf,1);
相关文章推荐
- 为什么二进制文件与文本文件存入同样的数据,文件大小差异会这么大?(from <<Thinking in C++>>'s execise)
- XCode can't open file (ifstream/ofstream) in C++ (XCode C++无法读写文件)
- C&python文件读写效率
- 解决 python 中读写文件的终极方案 UnicodeDecodeError: 'gbk' codec can't decode byte 0x9d in position 1270: illega
- pandas官方文档API参考的读写各类文件的API介绍 (1)(API reference IN&OUTPUT)
- C++读写ini配置文件GetPrivateProfileString()&WritePrivateProfileString()
- 廖雪峰python学习笔记10&&11:容错处理与文件读写
- 第十一周:( LeetCode567) Permutation in String(c++ && python)
- C++读写配置文件"*.ini
- 【leetcode】419. Battleships in a Board(C++ & Python)
- python/c/c++ 二进制文件读写
- C++读写文件代码自动生成器(python3完成)
- 【Python】修改文件并立即写回到原始位置(inplace读写)
- C++读写ini配置文件GetPrivateProfileString()&WritePrivateProfileString()
- ini文件纯C++读写代码
- c++ 文件读写简单示例
- ini文件纯C++读写代码
- [C++]文件读写操作
- 纯c++读写文件方式
- C++文件读写