3

我想使用 MATLAB 的fwrite命令更改大型二进制文件中几个字节的值。我想要做的是使用以下方法打开文件:

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

然后使用以下命令读取文件:

fread(fid,NUM,'int32');

这一切都有效。一旦到达要写入(覆盖)下一个字节的值的文件位置,我将使用以下命令:

fwrite(fid,variable_name,'int32');

然后我关闭文件:

fclose(fid);

所以然后我回去重新读取文件,这些字节没有改变!

那么这不可能吗?还是'r+'使用错误的东西?

4

2 回答 2

7

从文档中fopen

要读取和写入同一文件:

  • permission使用包含加号的值打开文件, '+'
  • 在读写操作之间调用fseek或。frewind例如,不要调用fread后跟fwrite,或fwrite后跟fread,除非您在它们之间调用fseekfrewind

简而言之,您需要在调用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);
于 2009-06-08T20:52:31.543 回答
0

当您阅读以了解要更改哪个字节时,请计算您必须跳过的字节数(例如,每个 int 或 float 4 个字节)。

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);
于 2017-04-10T21:17:31.063 回答