TweetFollow Us on Twitter

CopyFile XCMD
Volume Number:5
Issue Number:10
Column Tag:HyperChat™

Related Info: File Manager

XCMD Corner: CopyFile

By Donald Koscheka, Arthur Young & Co., MacTutor Contributing Editor

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

CopyFile XCMD

From time to time I monitor the developer forums on AppleLink and MacNet to see what the rest of the Macintosh development community is up to. Recently, Richard Greenawalt of Foremost Computer Systems issued a request for some help. It seems he needed a routine that copies Macintosh files, data fork, resource fork and finder information.

Not one to miss an opportunity to write an interesting XCMD, I 'linked Rick back and told him that I would be happy to write the routine for him.

The moral of the story is: ask and you might receive. If you need some help with an XCMD or if this column just doesn’t do it for you, let me know; I will be more than happy to help you out. Although I am up on AppleLink, I prefer to use MacNet (KOSCHEKA). If you don’t have access to a modem, write me care of MacTutor.

Copying a Macintosh file is not difficult as long as you keep in mind that Mac files are really two files in one. Each file on the Macintosh has a split personality - the data fork and the resource fork. Although the two forks act as one entity, the file manager treats them as separate files.

CopyFile is a handy little XCMD that lets you copy files from Hypercard. Actually the routine is written to work from any programming milieu which is why I’ve split it into two listings. The first consists of the Hypercard interface. Note that you need to pass both the file name and the working directory id. The second listing contains the actual code, void of any references to Hypercard. This approach lets me build libraries of usable routines that I can use with or without Hypercard, and I intend to use it for all future listings.

The CopyFile function expects to see the name of the input file, the name of the output file and the working directory id’s of both. This gives you some flexibility in naming the copy as well as deciding what folder to put it in. For example, you can concatenate the name of the input file to “copy of “ so that the duplicated file is called “copy of file”. Put this concept in a loop and you get the finder like capability of creating files and naming them “copy of ... “ , “copy of copy of ...” and so on. I chose not to implement this approach because I think the user should have the opportunity to specify the name of the copied file.

Although there are several ways to go about copying a file, I chose a path that goes something like this: First, get the collective size of the data and resource fork along with the finder information about the input file. Using this information, attempt to create a file that is as large as the input file (ie as large as the data and resource fork combined). If the space can be allocated, then copy each fork in turn. If not, delete the newly created file and quit.

Space for each fork is allocated before we do the copy so that we can determine a priori whether the file will fit. To be safe, we reposition the file mark at the beginning of the file before we start copying. If, for any reason, the file copy fails, delete what remains of the file and return the error message to the caller.

The real work is done by the function, CopyFork. This routine will attempt to read the entire fork into a single buffer. Failing that, it divides the size in half until enough memory can be allocated to read some of the fork. Note that copyfork attempts to allocate a buffer large enough to read the entire fork into memory. If that much memory is not available, it keeps dividing the original size by two until a large enough buffer can be allocated.

That’s file copying in a nutshell. It’s not particularly difficult once you realize that you’re really copying two files - the data fork and the resource fork. I’ve tried it with files up to 4 megabytes in size and it works fine.

/**********************************/
/* File: FileCopy.c*/
/* param0 = file reference num*/
/* ( file is open) IN:    */
/* params[0]= name of input */
/* params[1]= wdid of input */
/* params[2]   = name of output  */
/* params[3]   = wdid of output  */
/**********************************/
#include<MacTypes.h>
#include<OSUtil.h>
#include<MemoryMgr.h>
#include<FileMgr.h>
#include<ResourceMgr.h>
#include<pascal.h>
#include<string.h>
#include  “HyperXCMD.h”
#include“HyperUtils.h”

pascal void main( paramPtr )
 XCmdBlockPtr  paramPtr;
/*****************************
*params[0]= name of input 
*params[1]= wdid of input 
*params[2]  = name of output
*params[3]  = wdid of output
*****************************/
{ OSErr err;
 short  inWD;
 short  outWD;
 long   temp;
 Str31  errCode;
 char   inFile[256];
 char   outFile[256];
 paramPtr->returnValue = 0L;
 /*** (1) Get input parameters     ***/
 HLock( paramPtr->params[0] );
 ZeroToPas( paramPtr, *(paramPtr->params[0]), &inFile );
 HUnlock( paramPtr->params[0] );
 inWD = (short)paramtoNum( paramPtr, 1 );
 HLock( paramPtr->params[2] );
 ZeroToPas( paramPtr, *(paramPtr->params[2]), &outFile );
 HUnlock( paramPtr->params[2] );
 outWD = (short)paramtoNum( paramPtr, 3 );
 temp = (long)CopyFile( inFile, inWD, outFile, outWD );
 /*** Flush the output volume ***/
 err = FlushVol( 0L, 0 );
 NumToStr( paramPtr, temp, &errCode );
 paramPtr->returnValue = PasToZero( paramPtr, &errCode );
}

LISTING 1: CopyFile XCMD.


OSErr CopyFork( inref, outref, siz )
 short  inref;   short  outref;  longsiz;
/*****************************
* Given that the caller has opened
* a fork and passed you the names of 
* the input, copy the number of bytes
* from the input fork to the output 
* fork.
* The input mark should be set to 
* start of fork.
* We use a “semi-smart” algorithm
* to do the copy.  If the entire
* fork can be copied, we try doing 
* that, otherwise, we keep dividing
* the size by two until we get enough
* room to read some data in.
******************************/
{
 OSErr  rd_err   = noErr;
 OSErr  wrt_err  = noErr;
 long   rd_len;  /*** actual bytes read ***/
 Ptr    inbuf;
 /*** make sure that the size is even ***/
 if( siz % 2 )
 ++siz;
 if( siz > 0 ){
 do{
 inbuf = NewPtr( siz );
 if( !inbuf )
 siz = ( siz >> 1 );
 }while( !inbuf );
 /*** inbuf is the buffer that we  ***/
 /*** read the data into. If not   ***/
 /*** allocated, don’t attempt to do ***/
 /*** the read   ***/
 if( inbuf ){
 do{
 rd_len = siz;
 rd_err = FSRead( inref, &rd_len, inbuf );
 wrt_err= FSWrite( outref, &rd_len, inbuf );
 }while( !rd_err && !wrt_err );
 
 DisposPtr( inbuf );
 }
 }
 return( wrt_err );
}

OSErr CopyFile( inFile, inWD, outFile, outWD )
 char   *inFile;
 short  inWD; char *outFile;
 short  outWD;
/*****************************
* (1) Determine the size of the input 
* file. 
* (2) Attempt to allocate that 
* much space for the output file.
* (3) If allocation successful,
* create the output file.
* (4) Once the file is created,
* copy the data fork, the resource
* fork and the finder information
* from the input file.
* The file will be called “copy of...”
* Each time we create the file, first
* see if that name exists, if so, keep
* sticking “copy of” onto the name.
******************************/
{
 OSErr  err;
 OSErr  err2;
 short  inref;
 short  outref;
 long   data_eof = 0L;
 long   rsrc_eof = 0L;
 FInfo  fndrinfo;
 /*** (2) Determine how big the input file is ***/
 if( (err = FSOpen( inFile, inWD, &inref )) == noErr){
 err = GetEOF( inref, &data_eof );
 err = FSClose( inref );
 } 
 if( (err = OpenRF( inFile, inWD, &inref )) == noErr ){
 err = GetEOF( inref, &rsrc_eof );
 err = FSClose( inref );  
 }
 /*** (2) Create  output file and allocate space***/
 if( ( err = GetFInfo( inFile, inWD, &fndrinfo ) ) != noErr )
 return( err );
 if( ( err = Create( outFile, inWD, fndrinfo.fdCreator, fndrinfo.fdType 
)) != noErr )
 return( err );
 /*** (3) Try to allocate enough space for both***/
 /*** forks. Note that if we get enough space. ***/
 if( (err = FSOpen( outFile, outWD, &outref )) != noErr)
 return( err );
 if( (err = SetEOF( outref, data_eof  )) != noErr ){
 err2 = FSClose( outref );
 err2 = FSDelete( outFile, outWD );
 return( err );
 }
 err2   = FSClose( outref );
 err  = OpenRF( outFile, outWD, &outref );
 if( (err = SetEOF( outref, rsrc_eof  )) != noErr ){
 err2 = FSClose( outref );
 err2 = FSDelete( outFile, outWD );
 return( err );
 }
 err2 = FSClose( outref );
 /*** (4) Copy the Data fork***/
 err  = FSOpen( inFile, inWD, &inref );
 if( !err ){
 err2   = SetFPos( inref, fsFromStart, 0L );
 err    = CopyFork( inref, outref, data_eof );
 err2   = FSClose( inref );
 err2   = FSClose( outref );
 }
 if( err ){
 err2 = FSDelete( outFile, outWD );
 return( err );
 }
 /*** (5) Now copy the resource fork ***/
 err  = OpenRF( inFile, inWD, &inref );
 if( !err ){
 err2   = SetFPos( inref, fsFromStart, 0L );
 err  = OpenRF( outFile, outWD, &outref );
 err    = CopyFork( inref, outref, rsrc_eof );
 err2   = FSClose( inref );
 err2   = FSClose( outref );
 }
 if( err ){
 err2 = FSDelete( outFile, outWD );
 return( err );
 }
 return( noErr );
}

LISTING 2: CopyFile and CopyFork Functions.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more

Jobs Board

Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular 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
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.