Mel Script - Reading Binary Data




All file IO in mel requires the use of fopen and fclose to open and close files on the hard drive. When reading binary data we need to use fread. There are a few small issues you should be aware of, firstly mel is a high level language so you don't get the low level control you need over the binary data. For example, it is impossible to read a 4 byte float to the file since all floats in mel are stored as 8byte doubles.





Example 1 : using fread

All binary file writing in mel, uses fread to read the binary data from a file.



		// construct the full path to a file
		$filename = (`internalVar -userTmpDir` + "temp.dat");
		// open the file for writing
		$file = `fopen $filename "rb"`;

		// variables to store the data read from the file
		string $s;
		int $i;
		float $f;

		// fread takes two parameters, the file ID and the variable to read into.
		// The data read is actually returned from fread. The variable is 
		// required as an argument however, since Maya needs to determine what data
		// type to read from the file.
		$s = `fread $file $s`;
		$i = `fread $file $i`;
		$f = `fread $file $f`;

		// close the file
		fclose $file;



I apply the general rule that if you need to be doing binary file IO within mel, you should probably be thinking about writing a Maya plugin!