Re: Opposite of ReadList[ ... ,Byte]?
- To: mathgroup at smc.vnet.net
- Subject: [mg50353] Re: Opposite of ReadList[ ... ,Byte]?
- From: Bill Rowe <readnewsciv at earthlink.net>
- Date: Sun, 29 Aug 2004 03:54:00 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
On 8/28/04 at 4:38 AM, chris.purcell at drdc-rddc.gc.ca (Christopher Purcell) wrote: >John: I have made some use of binary files with decent success >using Version 4.2, but after Version 5 came out - my favorite >little binary read/write routine broke and I have not had time to >study why. Here are some trivial examples of creating and reading >binary files with the Utilities`BinaryFiles package which may be >instructive. These work ok for little test cases except for one >anomaly, which is noted. >(* Generate a binary file containing a header and 256 Random 8 bit >integers *) >Needs["Utilities`BinaryFiles`"]; >header="This is a dummy file header of length 40" >StringLength[header] data=Table[Random[Integer,{0,255}],{256}] (* >here are 256 random 8 bit integers *) >stream=OpenWriteBinary["test.bin"]; Length[data] >WriteBinary[stream,header, >ByteConversion\[Rule](ToBytes[#,StringConvert\[Rule]CString]&)]; >WriteBinary[stream,data, >ByteConversion\[Rule](ToBytes[#,IntegerConvert\[Rule]Int8]&)]; >Close["test.bin"]; >(* Read a binary file containing a known header, and 256 integers >(8 bit) *) >stream=OpenReadBinary["test.bin"]; >FromCharacterCode[ReadListBinary[stream,Byte,40]] (* >read the header *) >ReadListBinary[stream,Byte,1] (* why did this 0 get inserted? *) >ReadListBinary[stream,Int8] (* >read back the data *) >Close[stream]; >it was necessary to read an extra byte after the header, which gets >read back as a 0. I don't know why this extra byte is there. The extra 0 byte is there because you converted the header to a CString and wrote that to the file. In C, strings are terminated with a null byte, O. If you modify your read routine as follows: stream=OpenReadBinary["test.bin"]; ReadBinary[stream, CString] ReadListBinary[stream, Int8] Close[stream]; you will get back what you wrote in without the extra 0 byte -- To reply via email subtract one hundred and four