【问题标题】:length indicator with binary mode in C++C ++中具有二进制模式的长度指示器
【发布时间】:2014-05-23 18:14:59
【问题描述】:

使用 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);

这是对的吗?以及如何正确读取它,我似乎无法正确读取代码,请帮忙?

【问题讨论】:

  • 使用IDStr.c_str()获取字符串的内容,而不是&amp;IDStr
  • 如果您需要阅读代码方面的帮助,您需要展示您迄今为止所尝试的内容。
  • 您写的第一件事是size_t,所以这是您需要阅读的第一件事。 string 不是 size_t,也不是 char *
  • 阅读到底有什么问题?

标签: c++ file binaryfiles


【解决方案1】:

写字符串...

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;

【讨论】:

  • 不必要的演员表。不是异常安全的,不处理嵌入的空值,语法错误。
  • @AlanStokes,修复了语法错误。谢谢你让我知道。演员表是必要的。 istream::readostream::write 期望 char* 作为参数类型。如果没有强制转换,您应该得到编译器错误。我不知道你为什么认为它不能处理嵌入的空值。能详细点吗?
  • IDStr.c_str() 返回正确的类型,因此您不需要在那里进行强制转换(最好将char const * 强制转换为write)。 IDStr = s 将在它看到的第一个零字节处停止;你知道你有多少字节,所以你可以打电话给assign
  • 如果您现在从读取缓冲区中丢弃无用的空字节并用向量替换它,您会更接近。
  • @UlrichEckhardt 也许我遗漏了一些明显的东西,但这对我来说根本没有意义。如果字符串可以包含嵌入的空字符,您是否建议终止空字符无用?
猜你喜欢
  • 2016-11-07
  • 2010-11-28
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2019-03-04
  • 2019-04-20
  • 2013-01-01
相关资源
最近更新 更多