将向量的后半部分写入std :: ofstream [英] Write last half of the vector to std::ofstream

查看:183
本文介绍了将向量的后半部分写入std :: ofstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写代码以将向量写入文件。我的目标是将向量的后半部分写入文件,然后基于偏移量写入前半部分。下面的代码给出了分段错误。

I am writing code to write a vector to file. My aim is to write the last half of the vector to file first and then the first half based on offset. The code below gives me segmentation fault.

std::vector<uint8_t> buffer_(1000); // the vector is filled with values
int offset_ = 300;
std::ofstream output_file (file_name.c_str(), std::ofstream::out | std::ofstream::binary);
if (output_file.is_open()) {
    output_file.write(reinterpret_cast<const char*>(&buffer_[offset_]), (buffer_.size() -offset_)*sizeof(uint8_t));
    // segmentation fault on the line above
    output_file.write(reinterpret_cast<const char*>(&buffer_[0]), (offset_)*sizeof(uint8_t));
}

有人可以告诉我代码有什么问题吗?

Can somebody tell me whats wrong with the code?

推荐答案

您首先将偏移视为一个[0为基础]数组索引(& buffer_ [300] ),但是立即将其作为一个[1为基础]的元素计数( buffer_.size() - 300 )。这将导致从301 st 元素开始读取700个元素,该元素超过向量末尾一个元素。

You start by treating the offset as a [0-based] array index (&buffer_[300]) but then immediately treat it as a [1-based] element count (buffer_.size()-300). This is going to result in reading 700 elements starting at the 301st element, which goes past the end of your vector by one element.

从任何一个参数中减去一个,取决于offset的实际意义。

Subtract one from either of the arguments, depending on what you actually mean by "offset".

你应该习惯于在纸上完成这个基本数学,问题。

使用调试器不会受到伤害,无论是!

You should get used to working out this basic maths on paper when you have a problem.
Using your debugger wouldn't hurt, either!

这篇关于将向量的后半部分写入std :: ofstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆