我想使用 MATLAB 的 fwrite
命令更改大型二进制文件中几个字节的值。我要做的是使用以下方法打开文件:
fopen(filename,'r+',precision);
然后使用以下命令读取文件:
fread(fid,NUM,'int32');
这一切都有效。一旦我到达我想要写入(覆盖)下一个字节值的文件位置,我使用命令:
fwrite(fid,variable_name,'int32');
然后我关闭文件:
fclose(fid);
然后我回去重新读取文件,这些字节没有改变!
这不可能吗?还是 'r+'
使用不当?
最佳答案
来自 fopen
的文档:
To read and write to the same file:
- Open the file with a value for
permission
that includes a plus sign,'+'
.- Call
fseek
orfrewind
between read and write operations. For example, do not callfread
followed byfwrite
, orfwrite
followed byfread
, unless you callfseek
orfrewind
between them.
简而言之,您需要调用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);
关于file - 如何同时读取和写入二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/966711/