How to binary clone a file using fread and fwrite commands

조회 수: 2 (최근 30일)
TripleSSSS
TripleSSSS 2020년 7월 22일
답변: Walter Roberson 2020년 7월 23일
Hey there
I'd like to edit a binary file in a certain locaiton in the file, however before I start I'd like to clone a file using fread and fwrite commands.
I wrote a script that does that in matlab, I use the fread and fwrite commands with binary flag.
I compare the source and desitnation files with beyhond comapre - the files are not identical.
What am I doing wrong here? I simply read and write the same charecter.
you can simply using a random binary file for this example
regards
S
%%
clearvars;
% binary open a bin file
binayFilePath = 'D:\srcFile.Bin';
destinationBinaryFile = "D:\dstFile.Bin";
readFileId = fopen(binayFilePath, 'rb');
assert(readFileId > 0);
writeFileId = fopen(destinationBinaryFile, 'wb');
assert(writeFileId > 0);
%%
while ~feof(readFileId)
fileData = fread(readFileId, 1, 'bit64');
writeCount = fwrite(writeFileId, fileData, 'bit64');
end
fclose(readFileId);
fclose(writeFileId);
  댓글 수: 2
J. Alex Lee
J. Alex Lee 2020년 7월 22일
Why not just use the system copy command or matlab copyfile function?
Steven Lord
Steven Lord 2020년 7월 22일
J. Alex Lee, please post this as an Answer so we can vote for it and/or add comments related to this suggestion.

댓글을 달려면 로그인하십시오.

답변 (2개)

J. Alex Lee
J. Alex Lee 2020년 7월 23일
For your application does it make sense to just copy the file using a system command or matlab's coyfile?
  댓글 수: 1
TripleSSSS
TripleSSSS 2020년 7월 23일
No.
I'd like to edit a binary file file the future - simply add few blocks here and there.
therefor - for making the opration right, it does make sence to binary copy with matlab...

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2020년 7월 23일
%%
% binary open a bin file
binayFilePath = 'D:\srcFile.Bin';
destinationBinaryFile = "D:\dstFile.Bin";
readFileId = fopen(binayFilePath, 'r'); %there is no 'b' flag
assert(readFileId > 0);
writeFileId = fopen(destinationBinaryFile, 'w');
assert(writeFileId > 0);
%%
buffersize = 1024;
while ~feof(readFileId)
fileData = fread(readFileId, buffersize, '*uint8');
writeCount = fwrite(writeFileId, fileData, 'uint8');
end
fclose(readFileId);
fclose(writeFileId);
The larger the buffer size that you use, the more efficient the I/O is.
You were using 'ubit64' as the precision. That is the same as 'ubit64=>double' which converted the uint64 to double, but uint64 to double loses values because double can only represent 53 bits.
As well, when you use ubit* then when you hit end of file if the count is not exhausted then it pads with bits of 0.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by