Find and replace (overwriting) to the middle of an existing binary file

36 ビュー (過去 30 日間)
I'm trying to open a binary file for replacing without erasing all the content. For example I can read my binary file and convert it to the struct as follows, what I want to do is that to replace data section with my own data:
if ~exist('filename', 'var')
error(['''' filename ''' does not exist']); end
% Open file
fclose all;
fid = fopen(filename);
if fid < 3; error 'Error while opening file'; end
% Read one property at the time
while ~feof(fid)
% Read field name (keyword) and array size
keyword = deblank(fread(fid, 8, 'uint8=>char')');
num = fread(fid, 1, 'int32=>double', 0, 'b');
% Read and interpret data type
conv = 'single=>double';
wsize = 4;
% Read data array, which may be split into several consecutive arrays
data = [];
remnum = num;
while remnum > 0
% Read array size
buflen = fread(fid, 1, 'int32=>double', 0, 'b');
bufnum = buflen / wsize;
% Read data and append to array
%%% REPLACE DATA WITH NEW DATA %%%%
data = [data; fread(fid, bufnum, conv, 0, 'b')]; %<<========HERE========
remnum = remnum - bufnum;
end
end
fclose(fid);

採用された回答

Jeremy Hughes
Jeremy Hughes 2021 年 3 月 28 日
fopen(filename,'a') % append mode
Then use fseek to go to where you want to overwrite.
  4 件のコメント
Jeremy Hughes
Jeremy Hughes 2021 年 3 月 28 日
Yes, Walter is correct. I didn't read carefully enough. 'r+' mode allows you to move to a position in the file using fseek. fwrite should then write into the file at that position
Behzad Hosseinzadeh
Behzad Hosseinzadeh 2021 年 3 月 29 日
@Walter Roberson thanks for your great explanation. It works for me now.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLow-Level File I/O についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by