Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dealing with binary files in perl 1

Status
Not open for further replies.

icrf

Programmer
Dec 4, 2001
1,300
0
0
US
What the script should do is strip off the header of a number of targa files, concatenate what's left together, and then write a new header for the final file. The only part of this that is causing me problems is writing a new header. I know what each and every byte in the 18 byte header needs to look like, but how do I tell perl to write 240 (or 0x00f0) to the output file in binary and actually have the binary file contain that information? I re-wrote this in C just to make sure the logic of it all is correct, and it works perfectly fine. Here's kind of what I'm doing:
$temp = 0x00f0;
write(FH,$temp,2);
This should take the value in the scalar $temp and write it to where the file handle FH is currently pointing for a size of two bytes, correct? It's certainly not working that way. Octal display (od -x bin) of the file isn't producing the 0x00f0 that the similar C code can do, it's writing 0x3432. Make any sense to anyone?
 
Hi,

write is not the opposite of read (see documentation). You should use the following code:
Code:
my $temp = pack ('n', 0x00f0);
syswrite (FH, $temp, 2);
Please be careful with syswrite. It shouldn't be mixed with other write statements (see documentation).

Thomas
 
Well, I started doing it by "\xf0" and the like, but that only works one byte at a time, so your method of packing is much quicker, easier, and cleaner. I'm still pretty new to perl as a language. I'm used to C where nothing fakes what it is. A short int is a two byte integer, never anything else. Thanks a lot for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top