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

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.