gpt4 book ai didi

c++ - 带或不带 istreambuf_iterator 的 ifstream 有什么区别?

转载 作者:行者123 更新时间:2023-11-30 01:49:30 26 4
gpt4 key购买 nike

我需要读取一个包含标题和数据的二进制文件(一次性)。在 C++ 中有多种读取文件的方法,我想知道哪种方法最快、更可靠。我也不知道 reintrerpret_cast 是否是将原始数据转换为结构的最佳方式。

编辑: header 结构没有任何功能,只有数据。

ifstream File(Filename, ios::binary);    // Opens file

if (!File) // Stops if an error occured
{
/* ... */
}

File.seekg(0, ios::end);
size_t Size = File.tellg(); // Get size
File.seekg(0, ios::beg);

这是没有 istreambuf_iterator 的 ifstream

char* Data = new char[Size];

File.read(Data, Size);
File.close();

HeaderType *header = reinterpret_cast<HeaderType*>(Data);

/* ... */

delete[] Data;

这是带有 istreambuf_iterator 的 ifstream

std::string Data;    // Is it better to use another container type?

Data.reserve(Size);
std::copy((std::istreambuf_iterator<char>(File)), std::istreambuf_iterator<char>(),
std::back_inserter(Data));

File.close();

const HeaderType *header = reinterpret_cast<HeaderType*>(Data.data());

在网上也找到了这个

std::ostringstream Data;
Data << File.rdbuf();
File.close();
std::string String = Data.str();

const HeaderType *header = reinterpret_cast<HeaderType*>(String.data());

最佳答案

将文件内容读入 char*然后执行 reinterpret_castHeaderType*这不是一个好主意。

来自标准:

5.2.10 Reinterpret cast

...

7 An object pointer can be explicitly converted to an object pointer of a different type70. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void. Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

在您的情况下,如果 HeaderType 的对齐要求比 char 更严格,你会遇到未定义的行为。

如果你有选择,我会建议。

  1. 先阅读标题。

    HeaderType header;
    File.read(reinterpret_cast<char*>(&header), sizeof(HeaderType));
  2. 根据header的值读取其余数据.

关于c++ - 带或不带 istreambuf_iterator 的 ifstream 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29015708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com