0

我想实现将文件作为数组处理的想法。这是一段代码。在下一次写入之后,从流中返回相同的数据。如果我在写入数据后进行刷新,一切都会好起来的。告诉我为什么你需要一个闪光灯,你能没有它吗?

std::fstream _fs;
_fs.open("temp.bin", ios::binary | ios::in | ios::out |ios::trunc);
std::vector<double> vec(ELEMENT_SIZE);
std::streamoff _current_putpos = 0;
std::streamoff _end_pos = 0;
size_t size = ELEMENT_SIZE * sizeof(double);
for (size_t i = 0; i < SIZE; i++)
{
    for (size_t j = 0; j < 5; j++)
        vec[j] = (double)i;
    
    _fs.write((const char*)vec.data(), size);
    _end_pos += ELEMENT_SIZE * sizeof(double);
    _current_putpos = _end_pos;
}

for (size_t i = 0; i < SIZE; i++)
{
    //get at, after read at index 2 return always {1,1,1,1....} 

    std::streamoff sizeoffset = static_cast<std::streamoff>(i * size);
    std::streamoff seek = sizeoffset - _current_putpos;
    if (seek != static_cast<std::streamoff>(0))
        _fs.seekg(seek, std::ios::cur);

    memset(vec.data(), -1, size);
    _fs.read(reinterpret_cast<char*>(vec.data()), size);
    _current_putpos = _current_putpos + seek + static_cast<std::streamoff>(size);
    //set at
    for (size_t j = 5; j < 10; j++)
        vec[j] = (double)j;

    sizeoffset = static_cast<std::streamoff>(i * size);
    seek = sizeoffset - _current_putpos;
    if (seek != static_cast<std::streamoff>(0))
        _fs.seekp(seek, std::ios::cur);
    
    _fs.write(reinterpret_cast<const char*>(vec.data()), size);
    _current_putpos = _current_putpos + seek + static_cast<std::streamoff>(size);
}
4

0 回答 0