簡體   English   中英

C++ 用 fstream 替換二進制文件中的數據

[英]C++ replace data in binary file with fstream

我嘗試使用 C++ 和 fstream 庫替換二進制文件中的數據。 這個庫可以做到這一點嗎? 我想將 address: 0xB07 中的一字節文件更改為 1。

我編寫了以下代碼片段:

...

int address = 0xB07;
char * toChange = new char('0');

std::ifstream input(filename, std::ios::binary);
input.seekg(address);
input.read(toChange, 1);
input.close();

*toChange = (char)0x01;

std::ofstream output(filename, std::ios::binary);
output.seekp(address);
output.write(toChange, 1);
output.close();

...

我已經嘗試了此代碼的許多版本,但我仍然無法理解為什么字節沒有改變。

此代碼將刪除您的文件並將全新的內容放入其中。 問題出在

std::ofstream output(filename, std::ios::binary);

那是因為默認的打開模式是ios::out | ios::trunc ios::out | ios::trunc (參見例如: 帶有文件的輸入/輸出)這意味着文件被截斷為零字節。

然后你的 seek() 函數將他擴展到指定的大小(通常用零填充),最后output.write()在末尾寫入字節。

為了做你想做的事,我必須指定以下 ofstream 標志: std::ios::binary|std::ios::out|std::ios::in

我目前不能確定為什么需要std::ios::in ,抱歉......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM