c++ - 请求有关 C++ 11 中最先进的文件读取的示例

标签 c++ stl binaryfiles

<分区>

网络上有大量关于文件读取的例子。许多示例使用普通的旧 C 风格文件读取。其他示例使用 C++ 的东西,但我不知道它是否只是另一个普通程序员编写的教程,或者它是否是真正优秀的现代 C++。

那么,问题是:当今优秀的 C++ 程序员如何解决以下任务?

  1. 从二进制文件中读取一些表示单个原始类型变量的字节。
  2. 读取已知(但不是常数)长度的已知原始类型的数组。
  3. 当类型未知但字节长度已知时读取字节数组。例如,如果从文件中读取数组,然后将其传递给实际从中构建对象的函数。

最佳答案

How does a good C++ programmer nowadays solve the following tasks?

1.Read some bytes representing a single, primitive type variable from a binary file.

如果你想“读取一些代表某种类型的字节”,请使用 std::istream::read。使用 operator >> 读取该类型的一个实例(对于非 native 类型,您必须自己实现此运算符,但这是实现它的方法)。

2.Read an array of known primitive type of known (but not constant) length.

std::vector<YourType> YourVector;
KnownElementsCount = 100;
std::copy_n(std::istream_operator<YourType>{ in }, KnownElementsCount,
    std::back_inserter(YourVector));

如果你想读取长度为未知的数组:

std::vector<YourType> YourVector;
std::copy(std::istream_operator<YourType>{ in }, std::istream_operator<YourType>{},
    std::back_inserter(YourVector));

3.Read an array of bytes when the type is not yet known, but the length in bytes is known. For example, if the array is read from the file and then passed to a function which actually builds an object from it.

使用 std::istream::read;然后,从数据构建您的对象。

关于c++ - 请求有关 C++ 11 中最先进的文件读取的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24779748/

相关文章:

c++ - std::transform 返回的 std::pair 导致段错误

c++ - fread 在空值处终止中间读取。还读取超过预期数据的垃圾

visual-studio-2008 - 如何删除 Visual Studio 2008 中生成的所有二进制文件

c++ - 如何在 Eclipse CDT 中获取 C/C++ 程序的控制台输入

c++ - 在 C++ 中将正 float 组转换为带舍入的无符号短数组

c++ - 当数据有空格时,使用 C++ 的流运算符 >> 读取格式化数据

C - fread 似乎没有将数据读回内存

c++ - 遵循代码流程

c++ - Midl 编译器错误 : 2214

c++ - 为什么 std::max_element 需要 ForwardIterator?