c++ - C++中二进制模式的长度指示器

标签 c++ file binaryfiles

使用 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] = '\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;

关于c++ - C++中二进制模式的长度指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23835925/

相关文章:

c# - 是否存在用于将 CSS/HTML/jQuery 代码转换为 C++ 或 C# 代码的 C++ 或 C# 库?

python - 将脚本的目录添加到字符串中

html - 如何使 &lt;input type ="file"/> 可编辑?

java - 有没有一种快速的方法可以使用 java 获取设备上的所有音频文件?

c - 读取二进制文件,存入缓冲区,打印缓冲区内容

c# - 如何确保 DirectDraw 表面具有正确的文件格式?

c++ - "Id returned 1 exit status"错误 C++

c++ - 在另一个中使用 QAbstractListModel

c++ - C++类中的运算符重载

c - 如何在 C 中从二进制文件(使用 ab+)读取后打印结构成员