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

时间:2014-05-23 18:15:00

标签: 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);

这是对的吗?我怎么能从中得到适当的阅读,我似乎无法获得正确的阅读代码,请帮忙吗?

1 个答案:

答案 0 :(得分:2)

写下字符串......

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;