简体   繁体   中英

Reads data correctly but writes incorrectly

I am trying to read specific binary data (2 Bytes) of a file and this mission works well, the problem when rewriting that (2 Bytes) again in the same place. Unfortunately, it changes the entire file data to zeros.

Look at the following two screenshots:

Data before writing:

Data after writing:

The code:

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;
}

Why did that happen and how to resolve?


UPDATE :

I have appended std::ios::app to file mode, and zeros problem solved but the specific data that I want to update is not updated.

Using

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

will wipe out the data in the file since that is what ofstream does by default. You can use

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

to stop the data from being overridden but the issue with this is that file stream starts at the end of the file and pretends like the rest of the file doesn't exist, so you can seek back to the beggining and overwrite its contents.

What you can do instead is use a fstream like

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

To open the file in binary mode from the beginning without losing any contents. Then you can seek to where you want to write into the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM