正确读取数据但写入不正确

问题描述 投票:1回答:1

我正在尝试读取文件的特定二进制数据(2字节),并且此任务运行良好,在同一位置再次重写(2字节)时的问题。不幸的是,它将整个文件数据更改为零。

看看以下两个截图:

写入前的数据:

写完后的数据:

代码:

bool myClass::countChanger() {
    std::ifstream sggFileObj_r(this->sggFilePath, std::ios::binary);   
    if (!sggFileObj_r.is_open()) {
        std::cerr << strerror(errno) << std::endl;
        return false;
    }
    // Buffer variable
    unsigned short count;
    // Move the file pointer to offset 4
    sggFileObj_r.seekg(4);
    // Reading data 
    sggFileObj_r.read((char*)&count, sizeof(unsigned short));
    sggFileObj_r.close();
    //// ---------------------- ////
    std::ofstream sggFileObj_w(this->sggFilePath, std::ios::binary | std::ios::app);
    // Increase the buffer variable by one
    count += 1;
    // Move the file pointer again to offset 4
    sggFileObj_w.seekp(4);
    // Rewriting data again to the file after modification
    sggFileObj_w.write((char*)&count, sizeof(unsigned short));
    sggFileObj_w.close();
    return true;
}

为什么会发生这种情况以及如何解决?


更新:

我已将std::ios::app附加到文件模式,并且零问题已解决,但我想要更新的特定数据未更新。

c++ file read-write
1个回答
0
投票

运用

std::ofstream sggFileObj_w(this->sggFilePath, std::ios::binary)

将删除文件中的数据,因为这是ofstream默认执行的操作。您可以使用

std::ofstream sggFileObj_w(this->sggFilePath, std::ios::binary | std::ios::app);

停止数据被覆盖,但问题是文件流在文件末尾开始并且假装文件的其余部分不存在,因此您可以回到开始并覆盖其内容。

你可以做的是使用像fstream

std::fstream sggFileObj_w(this->sggFilePath, std::ios::binary | std::ios::out | std::ios::in);

从头开始以二进制模式打开文件而不丢失任何内容。然后,您可以寻找要写入文件的位置。

© www.soinside.com 2019 - 2024. All rights reserved.