Compress/Uncompress File Error

Recently, I was contacted by someone using compression/uncompression programs that I wrote (compress_test.m and uncompress_test.m). MATLAB generated an error and stopped during the run of the uncompression program.

  >> uncompress_test
  ??? Error using ==> fscanf
  Invalid size.

  Error in ==> readAfile at 144
  [c3, more_to_read] = fscanf(myfile, '%c', values2read);

  Error in ==> uncompress_test at 16
  [a3_huff, b1_huff, b2_huff, b3_huff, ...

This same code works on my computer. This is a weird kind of error -- two computers execute the same code, and have different results! I looked at the data file, and determined that it was a corrupted file.

I ran some tests on the remote computer, and found that it would not write character values above 127 correctly. Digging deeper, I found that MATLAB does allow a character encoding to be specified in the fopen command. And the problem stems from different computers using a different default encoding!

The problem is not hard to fix -- it requires specifying an 8-bit (and only 8-bit) character encoding in the readAfile.m and writeAfile.m programs. Specifically, the line to change in readAfile is:

  myfile = fopen(filename, 'r');

to

  myfile = fopen(filename, 'r', 'n', 'latin1');

Similarly, in program writeAfile, change line 10 to:

  myfile = fopen(filename, 'w', 'n', 'latin1');

This also applies to the project in chapter 10, with files readAfile2.m and writeAfile2.m.

It is not clear if this problem applies to all versions of MATLAB for Microsoft Windows, or just certain ones.

Or you can download the updated files here:
  readAfile.m
  writeAfile.m
  readAfile2.m
  writeAfile2.m
You will need the other programs found on the book's CD-ROM to make these work.


-Michael Weeks, August 2011, last revised: October 2011