file - 如何同时读取和写入二进制文件?

标签 file matlab file-io binary fwrite

我想使用 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 or frewind between read and write operations. For example, do not call fread followed by fwrite, or fwrite followed by fread, unless you call fseek or frewind 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/

相关文章:

matlab - 使用 mle() 估计自定义分布的参数

c++ - Mountain Lion 上的 Mex 文件 : explicit instantiation error

file-io - 如何将 Ada.Real_TIme.Time 转换为字符串?

javascript - 读取 "file"对象的内容?

image - 从目录加载所有图像

python - 如何从 Python 中的 zip 文件中读取 zip 文件?

Mysql 通过 PHP 给出 "Can' t create/write to file"错误

python - 将指针字典保存到文件

macos - Cocoa:如何创建 CFUrl/NSUrl 以从 ExtAudioFileOpenURL 的内存缓冲区中读取

arrays - C如何将.txt文件的内容放入二维数组