TweetFollow Us on Twitter

Sector Dumps
Volume Number:5
Issue Number:7
Column Tag:HyperChat™

XCMD Corner: Sector Dumps

By Donald Koscheka, Arthur Young & Company, MacTutor Contributing Editor

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Reinventing the wheel often provides an opportunity to embellish on the original design. Recently, I needed a file dump utility. Several packages are available “over the counter”, but I needed a utility that dumps the entire file without having to manually move from sector to sector as is the case with most commercial solutions. Moreover, I use file dump tools frequently enough that I could afford to spend the effort writing one for Hypercard.

I dump the file in a fairly typical way. Each line in the dump contains the “sector address” of the first byte on the line followed by the hexadecimal dump of 16 bytes followed by the ASCII interpretation of the data. Not all ASCII characters are “printable” so we replace non-printing characters with the “.”, yielding a cleaner display.

This month’s XFCN, FilePeek.c (listing 1) accepts two parameters. The first parameter is the reference number of the opened file; the second parameter is the sector you want dumped. HFS sectors are 512 bytes so filepeek returns 32 lines of 16 bytes apiece.

Dumping the entire contents of a file becomes a matter of calling FilePeek repeatedly for all the logical sectors in the file.

The first line in the dump tells us how many bytes were read in. This number can be equal to or less than a full sector. If line 1 contains less than a sector full of data, then you know that logical end of file is after the last byte read in.

The Hypertalk afficianado will realize that this code can easily be written in Hypertalk. I chose to commit my scheme to an XFCN only after discovering that the Hypertalk version was too slow for my purposes.

The dumping scheme is amazingly simple. Position the file mark at the beginning of the sector that you want to dump. If the start of the sector extends beyond end of file, do nothing and return to hypercard with a result of zero (no bytes were read in), otherwise read the sector into the buffer we allocated (buf).

The sector is presented to Hypercard as a series of haxadecimal characters. Hypercard contains a call back “NumtoHex” which converts an arbitrary run of data to a hex string. We lose portability when using a callback so you’ll need to write your own hexdump algorithm or dig one up in the toolbox.

FilePeek dumps two bytes at a time (4 hex digits). This is analogous to dumping the contents of a short. We can use a pointer to short (rPtr). To dump the ascii data, we use a char pointer (cPtr) to the same data.

The current line in the dump is assembled by first displaying the “sector address” of that line. The sector address is 512 * blk (blk = sector number).

The sector address is delineated by the “:” character. Following the sector address, we display 16 bytes of data in hexadecimal format. The data is grouped into 8 words.

The hexadecimal data is followed by the ascii representation of the line. If the character falls in the range of printing characters, we display the character, otherwise print a “.”. Characters below the space (0x020) are not normally considered printing characters. Likewise, Inside Macintosh indicates that no characters above $D8 have a printable format. Using the period to represent non-printing characters results in a less-cluttered looking dump.

We need to cycle the character pointer, cPtr, twice for every cycle on rPtr (a character is half a word). We accumulate the ascii data into a separate string which we then concatenate onto the end of the hex data.

Once the current line is assembled, we stick a carriage return on the end, block move it to the output data handle and then go to the next 16 bytes in the input stream. When the outer loop completes, outdata will contain 32 lines of 16 bytes apiece, suitable for framing.

Figure 1.

How you open and close a file from Hypercard is a matter of taste. I prefer to keep my interface to the file manager as clean as possible. This requires passing a filename and working directory id to the file manager’s FSOpen call and subsequently referring to the file by the reference number returned by FSOpen. To close the file, pass the reference number to FSClose (last month I provided an XFCN that will return a file name and working directory id from the standard file package).

Listings 2 and 3 are two simple XFCNs that open and close a file respectively. FileOpen returns a reference number if the file opened ok (0 otherwise). Pass this reference number to FilePeek along with the number of the sector you wish to dump.

Figure 1. is a sample card that I use to dump the contents of the file. The dump is presented in a mono-spaced font to keep it “clean-looking”. The forward and back arrows allow the user to “browse” sectors by moving 1 sector forward or backward. The scripts for theses two buttons is fairly obvious so I’ve left them to the reader. The scripts for open, close are contained in listing 4.

--1

-- file open button
on mouseUp
  global fileName, DirectoryID
  global fileRefNum, theSector
  
  put getFileNameToOpen() into it
  put item 1 of it into fileName
  put item 2 of it into DirectoryID
  put filename into card field “file name”
  
  if filename is not empty then
    Put FileOpen( fileName, DirectoryID ) into fileRefNum
  end if
  
end mouseUp

-- Go to Sector
on mouseUp
  global fileRefNum, theSector
  
  if filerefnum is empty then
    answer “You have to open a file first, silly!”
  else
    
    ask “Read what sector?” with “0”
    
    if (it is not empty) then
      put it into theSector
      Peekat theSector
    end if
  end if
  
end mouseUp

-- file close
on mouseUp
  global fileRefNum
  
  put FileClose( fileRefNum ) into it
  -- ignore the result of a closed file
end mouseUp

Listing 4. Scripts for the buttons

An interesting variation on this theme would be to dump the files in reverse order so that it prints in ascending order on the LaserWriter. Several easy solutions exist for this problem, and I’ll leave it as this month’s exercise to the reader. As a hint, I can think of two ways to do this off hand, one easy but inefficient, the second a little more challenging: (1) create a card for every sector (make sure your file is small first!) or (2) Find out how many sectors the file contains before starting the dump ( a wonderful opportunity to try your hand at XFCN writing).

Note on a bug in last month’s article:

Last month’s XFCN, GetFileName, incorrectly returns the working directory id of the file selected from SFGetFile. Change the call to GetFileNameToOpen to Read:

/* 1 */

if( GetFileNameToOpen(typs,numTypes,FileName,&FileWDID ) ){
 temp = (long)FileWDID & 0xFFFF;
 NumToStr( paramPtr, temp, &WDIDString );
 PtoCstr( WDIDString );
Listing 1:  FilePeek.c

/********************************/
/* File: FilePeek.c*/
/* */
/* Given the sector index into*/
/* an existing file, read the */
/* sector in and “dump” it to */
/* the screen    */
/* */
/* Paramters:    */
/* param0 = file referencenum */
/* ( file is open) */
/* param1 = sector number */
/* (1 sector = 512 bytes) */
/* ----------------------------  */
/* To Build:*/
/* */
/* (1) Create a project using */
/* this file as well as the */
/* XCMD.Glue.c file. (Set */
/* project type to XCMD (or */
/* XFCN) from the Project menu.  */
/* */
/* (2) Bring the project up to*/
/* date.*/
/* */
/* (3) Build Code Resource. */
/* */
/* (4) Use ResEdit to copy the   */
/* resource to your stack.*/
/********************************/

#include<MacTypes.h>
#include<OSUtil.h>
#include<MemoryMgr.h>
#include<FileMgr.h>
#include<ResourceMgr.h>
#include<pascal.h>
#include<strings.h>
#include  “HyperXCmd.h”
#include“HyperUtils.h”

#define SECTOR   512 /***size of input buffer ***/
#define NUMROWS  8 /***across each line***/
#define NUMLINES 32/***lines of data ***/
#define NUMBYTES 16/***#bytes per row of data***/
#define SPACE    0x020  /***the space character***/

long  paramtoNum();
void  appendChar();
void  CopyStrToHandle();
char  *CopyAscii();

pascal void main( paramPtr )
 XCmdBlockPtr  paramPtr;
{
 short  err;
 short  fref;
 short  lc; /* line count */
 short  rc; /* row count  */
 long   cnt;
 long   blk;/* sector number  */
 Handle outData;
 short  *rPtr;   /* per row */
 char   *cPtr;   /* for ASCII */
 char   *aPtr;   /* points to asciival */
 char   *buf;
 char   asciiStr[32];
 char   curntLine[256]; 
 Str31  numString;
 
 outData = 0L;
 if( paramPtr->paramCount == 2 ){  
 /*** expect two parameters ***/
 /*** (1) Get our input parameters ***/
 fref = (short)paramtoNum( paramPtr, 0 );
 blk   = paramtoNum( paramPtr, 1 );

 /*** (2) Read a buffer of data    ***/
 blk = blk * SECTOR;
 err = SetFPos( fref, fsFromStart, blk );
 if ( !err ){
 cnt = SECTOR;
 
 /*** We need to keep this data locked ***/
 /*** Since we can;t trust callbacks not     ***/
 /*** to move stuff, we allocate the ***/
 /*** buffer as non-relocatable.   ***/
 buf = NewPtr( cnt );
 err = FSRead( fref, &cnt, buf );
 
 if ( err != noErr &&  err != eofErr ){
 paramPtr->returnValue = 0L;
 return;
 }
 }
 
 /*** result is returned to hypercard as     ***/
 /*** a null terminated string***/
 outData = NewHandle( 0L );

 /*** (3) Start filling the output buffer    ***/
 *curntLine = ‘\0’;
 
 /*** first the number of bytes read in***/
 NumToHex( paramPtr, cnt, 4 , &numString );

 appendChar( PtoCstr( (char *)&numString), ‘\r’ );
 CopyStrToHandle( &numString, outData );

 /*** point to the input data ***/
 rPtr = (short *)buf;
 
 for( lc = 0;  lc < NUMLINES; ++lc ){
 *curntLine = ‘\0’;

 /*** blk is the sector address  ***/
 NumToHex( paramPtr, blk, 6, &numString );
 PtoCstr( (char *)&numString );
 strcat( curntLine, &numString );
 appendChar( curntLine, ‘:’ );
 appendChar( curntLine, SPACE );
 aPtr = asciiStr;
 blk += NUMBYTES;
 
 for( rc = 0; rc < NUMROWS; ++rc ){
 
 /*** convert eight shorts per row ***/
 /*** if we overrun the buffer, draw ***/
 /*** whatever data follows it...  ***/
 NumToHex( paramPtr, (long)*rPtr, 4 , &numString);
 strcat( curntLine, PtoCstr( (char *)&numString));
 appendChar( curntLine, ‘ ‘ );
 
 cPtr = (char *)rPtr;
 aPtr = CopyAscii( aPtr, *cPtr++ );
 aPtr = CopyAscii( aPtr, *cPtr++ );
 rPtr++;
 }
 
 *aPtr = ‘\0’; /*** terminate the ascii data ***/
 strcat( curntLine, asciiStr );
 appendChar( curntLine, ‘\r’ );
 
 /*** move  line into output buffer***/
 CopyStrToHandle( curntLine, outData );
 }
 
 DisposPtr( buf );
 }
 
 cnt = GetHandleSize( outData );
 *(*outData + cnt) = ‘\0’;
 paramPtr->returnValue = outData;
}

long  paramtoNum( paramPtr, i )
 XCmdBlockPtr  paramPtr;
 short  i;
/************************
* Given a handle to an input
* argument in the paramBlk
* return an integer representation
* of the data.
*
************************/
{
 Str31  theStr;
 
 HLock( paramPtr->params[ i ] );
 ZeroToPas( paramPtr, *(paramPtr->params[ i ]), &theStr );
 HUnlock( paramPtr->params[ i ] );
 return( StrToLong( paramPtr, &theStr ) );
}

void  appendChar( theStr, theChar )
 char *theStr;
 char theChar;
/************************
* append the character passed
* to the end of the string 
************************/
{
 long len = strlen( theStr );
 char *theEnd;

 theEnd = theStr + len;
 *theEnd++  = theChar;
 *theEnd  = ‘\0’;
}

char  *CopyAscii( outStr, theChar )
 char *outStr;
 char theChar;
/************************
* if the character passed  
* in the input stream is a 
* printing character, append
* it to the output string,
* otherwise, append the ‘.’
*
* return the update output 
* string.
************************/
{
 if ( theChar >= SPACE  &&  theChar <= 0x0D8  ) 
 *outStr++ = theChar;
 else
 *outStr++ = ‘.’;
 
 return( outStr );
}

void CopyStrToHandle( theStr, hand )
 char *theStr;
 Handle hand;
/************************
* Copy the input data to the
* output handle.
*
************************/
{
 long cnt = strlen( theStr );
 long oldSize  = GetHandleSize( hand );

 SetHandleSize( hand, oldSize + cnt );
 BlockMove( theStr, *hand + oldSize, cnt );
}
Listing 2: FileOpen.c

/********************************/
/* File: FIleOpen.c*/
/* */
/* open the file whose name and */
/* working directory id are */
/* passed as parameters.  This*/
/* information can be obtained*/
/* using GetFileNameToLoad... */
/* */
/* Paramters:    */
/* param0 = file namenum  */
/* param1 = directory id  */
/* */
/* Out: */
/* File RefNum if opened, 0 */
/* otherwise*/
/* ----------------------------  */
/********************************/

#include<MacTypes.h>
#include<OSUtil.h>
#include<MemoryMgr.h>
#include<FileMgr.h>
#include<ResourceMgr.h>
#include<pascal.h>
#include<strings.h>
#include  “HyperXCmd.h”
#include“HyperUtils.h”

pascal void main( paramPtr )
 XCmdBlockPtr  paramPtr;
{
 char   *filename;
 Str31  str, fName;
 short  wdid, refnum;

 HLock( paramPtr->params[0] );
 ZeroToPas( paramPtr, *(paramPtr->params[0]), &fName );
 HUnlock( paramPtr->params[0] );
 
 /* convert the wdid to a usable form */
 HLock( paramPtr->params[1] );
 ZeroToPas( paramPtr, *(paramPtr->params[1]), &str );
 HUnlock( paramPtr->params[1] );
 wdid = (short)StrToNum( paramPtr, &str );
 
 if( FSOpen( &fName, wdid, &refnum) == noErr )
 NumToStr( paramPtr, (long)refnum, &str );
 else
 NumToStr( paramPtr, 0L, &str );

 paramPtr->returnValue = PasToZero( paramPtr, &str );
}
Listing 3:  FileClose.c

/********************************/
/* File: FileClose.c */
/* */
/* XCMD to access the file mgr*/
/* call FSClose  */
/* Paramters:    */
/* param0 = file reference from  */
/* the fileopen xcmd */
/* ----------------------------  */
/********************************/

#include<MacTypes.h>
#include<OSUtil.h>
#include<MemoryMgr.h>
#include<FileMgr.h>
#include<ResourceMgr.h>
#include<pascal.h>
#include<strings.h>
#include  “HyperXCmd.h”
#include“HyperUtils.h”

pascal void main( paramPtr )
 XCmdBlockPtr  paramPtr;
{
 short  refnum;
 char   str[256];
 
 /* convert the refnum to a usable form */
 HLock( paramPtr->params[0] );
 ZeroToPas( paramPtr, *(paramPtr->params[0]), &str );
 HUnlock( paramPtr->params[0] );
 refnum = (short)StrToNum( paramPtr, &str );
 
 /* Normally we should check the result      */
 /* code but it won’t kill us to ignore*/
 /* the reslt of a close file call */
 if ( FSClose(refnum) )
 ;
 paramPtr->returnValue = 0L;
}

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.