首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++中具有二进制模式的长度指示器

C++中具有二进制模式的长度指示器
EN

Stack Overflow用户
提问于 2014-05-23 18:14:59
回答 1查看 382关注 0票数 0

使用C++,我以二进制模式写入文件,使用如下所示的长度指示器方法:

代码语言:javascript
运行
复制
    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);

我是这样读的:

代码语言:javascript
运行
复制
    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);

是这样吗?我如何才能适当地阅读,我似乎不能正确的阅读代码,有什么帮助吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-23 18:42:14

写绳子..。

代码语言:javascript
运行
复制
size_t IDlength = IDStr.length();
stream.write ((char const*)(&IDlength), sizeof(size_t));
stream.write (IDStr.c_str() ,IDlength);

看绳子..。

代码语言:javascript
运行
复制
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] = '\0';

// 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;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23835925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档