正确读取数据但写入错误

时间:2019-05-01 20:04:54

标签: c++ file read-write

我正在尝试读取文件的特定二进制数据(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附加到文件模式,并且解决了零问题,但是我要更新的特定数据未更新。

1 个答案:

答案 0 :(得分: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);

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