views:

785

answers:

2

I want to change the value of a couple of bytes in a large binary file using matlab's fwrite command. What I am trying to do is open the file using fopen(filename,'r+',precision) then read down the file using fread(fid,NUM,'int32') (this all works). Once I get to the file position where I want to write (overwrite) the values of the next bytes, I use the command: fwrite(fid,variable_name,'int32'). Then I close the file:fclose(fid).

OK, so then I go back and re-read the file and these bytes haven't changed!

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

Thanks.

+6  A: 

From the documentation for FOPEN:

If you open a file in update mode (with a permission value that includes '+'), you must call fseek or frewind between read and write operations. For example, you cannot call fread followed by fwrite, or fwrite followed by fread, unless you call fseek or frewind between them.

In short, you need to call FSEEK before you call FWRITE. In fact, if you don't need to read anything from the file, I would just use FSEEK in place of your call to FREAD.

gnovice
A: 

Thanks for the help. The fseek command, did the trick. EXCEPT it still didn't work! WHat do I mean? The bytes change in memory, but it doesn't get written to the disk when I close the file with fclose (yes the file permissions are set right).

I am running it on a new macbook pro OS10.5.7 with MATLAB 7.5.0.338 (R2007b).

I ported the code to my Linux machine and viola! it works. So the fix is that I run it on the Linux box.

Weird! I would probably either search/post to The MathWorks newsgroup (http://www.mathworks.com/matlabcentral/newsreader/) to see if anyone else has had that problem or contact technical support (http://www.mathworks.com/support/contact_us/index.html#) and possibly submit a bug report.
gnovice