View Single Post
  #47 (permalink)  
Old 02-21-2008, 01:57 AM
prasannavigneshr prasannavigneshr is offline
D-Web Incredible
 
Join Date: Feb 2007
Posts: 1,321
prasannavigneshr is on a distinguished road
Send a message via MSN to prasannavigneshr
Thumbs up ColdFusion Tips & Tricks - Reading BINARY files in MX

Reading BINARY files in MX


Under Cold Fusion MX, you can treat Binary Files as Read-Only data. IE: You can read the file but you can't write to it.

However, it's not clear that you can do so. It was only doing some detective work after looking at the source code for MX's version of the CFDUMP tag did I figure it out.

When you read in a file using the BINARYFILE type in the <CFFILE> tag, you can access the binary data variable as a one dimensional array (each byte gets it's own row).

The binary data is stored in ASCII format - it stores the numerical value of the character. However, if the character has an ASCII value of 128 or higher, the internal representation has 256 subtracted from it. So, the value stored in the "binary" array ranges from -128 to 127.

Here's a UDF that will return the ASCII value of the position you specify. Note that this UDF the binary file as 1 base instead of 0 base. This means that the 1st byte in the file is referenced as 1 instead of 0.
Code:
<cfscript>
function Get(BVar,loc)
{
  if (isBinary(BVar) EQ "No") return 0;
  if (BVar[loc] GTE 0) return BVar[loc];
  return BVar[loc] + 256;
}
</cfscript>
If you want to display the character, use the Chr( ) function.

Example to display the ASCII value of the first 100 characters in a file.
Code:
<cffile action="READBINARY" file="C:\Test1.pdf" variable="Data">
<CFLOOP index="loop" from="1" to="100"><CFOUTPUT>#Chr(Get(Data,loop))#</CFOUTPUT></CFLOOP>
Note: This does not work in CF 5. Trying to manipulate the binary array will generate an error.
__________________
Prasanna Vignesh
MCPD | Web Developer
Reply With Quote