How can I read and write to a binary file at the same time?

I want to change the value of a pair of bytes in a large binary file using the MATLAB command fwrite. What I'm trying to do is open the file with:

fopen(filename,'r+',precision);

Then read the file using:

fread(fid,NUM,'int32');

It all works. As soon as I get to the file position where I want to write (overwrite) the values ​​of the following bytes, I use the command:

fwrite(fid,variable_name,'int32');

Then I close the file:

fclose(fid);

So, I go back and re-read the file, and these bytes have not changed!

So this is not possible? Or is it 'r+'wrong to use?

+3
source share
2 answers

From the documentation for : fopen

:

  • permission , '+'.
  • fseek frewind . , fread fwrite fwrite fread, frewind fseek frewind.

, fseek fwrite:

fid = fopen(filename, 'r+', precision);
data = fread(fid, NUM, 'int32');
fseek(fid, 0, 'cof');
fwrite(fid, variable_name, 'int32');
fclose(fid);

, , fseek fread. :

fid = fopen(filename, 'r+', precision);
fseek(fid, NUM*4, 'bof');
fwrite(fid, variable_name, 'int32');
fclose(fid);
+7

, , , , ( 4 int float).

bytesToSkip = 0;
not_the_value_you_want = true;
bytesPerValue = 4; %for a float or int

while not_the_value_you_want

...some code here...

  if 'this is it'

  not_the_value_you_want = false; % adapt this to your taste

  else

  bytesToSkip += bytesPerValue;

  end;

...maybe more code here...

end;

:

fileID = fopen('YourFile.bin','w+');
fseek(fileID,bytesToSkip,'bof'); %'bof' stands for beginning of file
fwrite(fileID,newValue);
fclose(fileID);
0

Source: https://habr.com/ru/post/1710020/


All Articles