Write last half of the vector to std::ofstream

强颜欢笑 提交于 2019-12-10 12:26:30

问题


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?


回答1:


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.

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!




回答2:


The functionality sought by this question is already implemented in rotate and rotate_copy. As a general rule re-implementing behavior already in the standard is wasteful and/or can be fraught with error, as is demonstrated by this question.

Since rotate_copy only uses ForwardIterators for it's input iterators, this answer can be leveraged through the simple use an ostreambuf_iterator. So this can be done instead of the two writes in the question:

const char* pBufferBegin = reinterpret_cast<const char*>(&*buffer_.data());

rotate_copy(pBufferBegin, pBufferBegin + offset_, pBufferBegin + buffer_.size(), ostreambuf_iterator<char>(output_file));


来源:https://stackoverflow.com/questions/31939757/write-last-half-of-the-vector-to-stdofstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!