【问题标题】:Which is the best way to read binary file content to std::string? [duplicate]将二进制文件内容读取到 std::string 的最佳方法是什么? [复制]
【发布时间】:2011-06-30 08:44:46
【问题描述】:

可能重复:
How to use istream with strings

std::ifstream ifile(absolute_file_path.c_str(),std::ios::binary | std::ios::in | std::ios::ate);
if (ifile.is_open()==false) 
{
    throw std::runtime_error("Unable open the file.");
}
std::stirng file_content;
//here I need good way to read full file to file_content
//note: the file is binary
ifile.close();

这是我知道的方式:

1.可能不安全

file_content.resize(ifile.tellg());
ifile.seekg(0,std::ios::beg);
if(!ifile.read(const_cast<char *>(file_content.data()), file_content.size()));
{
    throw std::runtime_errro("failed to read file:");
}
ifile.close();

2.慢

file_content.reserve(ifile.tellg());
ifile.seekg(0,std::ios::beg);
while(ifile)
{
    file_content += (char)(ifile.get());
}

【问题讨论】:

标签: c++ file


【解决方案1】:

如果文件是二进制文件,它可能包含'\0',这是一个包含在std::string 中的奇怪字符。尽管我认为您可以这样做,但您会提出问题,因为在 std::string 上的某些操作采用了以 null 结尾的 const char*。相反,请使用std::vector&lt;char&gt;,这是一种更安全的方式。

如果您仍然使用字符串,只需执行一个循环调用 std::string::append(size_t, char)

while(!ifile.eof()) {
   contents.append(1, ifile.get());
}

编辑:我认为你也可以做一些事情:

std::string contents(std::istreambuf_iterator<char>(ifile), std::istreambuf_iterator<char>());

【讨论】:

  • 从简单的解决方案开始,如果您有实际数据显示它很慢,请稍后进行优化。过早的优化是万恶之源——DonaldKnuth
  • 哪些std::string 操作采用const char*?一些重载允许来自char 数组的输入,但std::string 是NULL 安全的`
  • 构造函数std::string(const char* s)operator+=(const char* s)等都以const char*作为参数,这意味着如果参数有一个NULL那么它将被解释为字符串切片的一部分你真的想要。
  • 当然,但它们只是为了方便而提供,std::string 重载存在(并且是首选)相同的输入。以 NULL 结尾的 std::string 没有任何内在的东西。这里的类比是,如果您将 C 字符串复制到 std::vector&lt;char&gt; 中,您仍然仍然必须使用 strlen。另请注意,您可以为第一个函数提供明确的大小。
【解决方案2】:

你应该清楚二进制文件和字符串。您是要读取该文件的内容,还是要将文件的二进制表示形式读取为字符串?通常unsigned char[] 缓冲区用于存储二进制文件的内容。而string用于存储文本文件的内容。

【讨论】:

  • 为什么不呢?它是无符号字符,在 Windows 中是字节。请专注于想法,而不是这种细节!
  • 好吧,我下次要小心点:-)
  • Noooooo 不推荐使用原始数组。绝对没有理由这样做。
  • 为什么不呢?这取决于你的目的。通常我们读取二进制文件以关心每个字节(左右)来处理数据。因此,使用原始数组可能有助于更轻松、更快地处理数据。如果你事先知道文件大小不会大于字节数,只需使用固定数组,否则,使用动态数组代替(有很多方法可以做到这一点,如果不需要我不会详细说明)
  • 原始char[] 或动态分配的数组(char*) 是否比vector&lt;char&gt; 快得多(如果有的话)?因为vector&lt;char&gt;具有明显的优势,最重要的是它不会忘记自己的大小,并且不需要手动管理内存。
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2014-11-03
  • 2011-10-22
  • 1970-01-01
相关资源
最近更新 更多