长度指示器与二进制模式在c++中
length indicator with binary mode in C++
使用c++,我以二进制模式写入我的文件,使用长度指示符方法如下:
ostringstream ID;
ID << b.getID(); //where b.getID() returns unsigned long
string IDStr = ID.str();
size_t IDlength = IDStr.length();
stream.write ((char *)(&IDlength), sizeof(size_t));
stream.write ((char *)(&IDStr),IDlength);
我是这样读的:
string IDStr,ID;
stream.read ((char *) (&IDStr), sizeof(size_t));
int Result;
stringstream convert(IDStr);
if ( !(convert >> Result) )//give the value to Result using the chars in string
Result = 0;//if that fails set Result to 0
stream.read ((char *)ID,Result);
对吗?我怎么才能正确地读取它,我似乎不能正确读取代码,请帮忙?
写字符串…
size_t IDlength = IDStr.length();
stream.write ((char const*)(&IDlength), sizeof(size_t));
stream.write (IDStr.c_str() ,IDlength);
读取字符串…
size_t IDlength;
stream.read ((char *)(&IDlength), sizeof(size_t));
// Allocate memory to read the string.
char* s = new char[IDlength+1];
// Read the string.
stream.read (s, IDlength);
// Make sure to null-terminate the C string.
s[IDlength] = ' ';
// Create the std::string using the C string.
// Make sure the terminating null character is
// not left out.
IDStr.assign(s, IDlength+1);
// Deallocate memory allocated to read the C string.
delete [] s;
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 在C++的一系列数字中查找重复模式
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- С++ wxWidgets:代码架构,设计原则和模式
- 以只读模式打开数据库时SQLITE_CANTOPEN错误