Ejemplo n.º 1
0
Boolean PICloseFileAndMakeAlias (FSSpec& fsSpec,
					 FileHandle fRefNum, Boolean sameNames,
					 Boolean *dirty, AliasHandle *alias, short *result)
{
//	FSSpec			spec;
	OSErr			gotErr;
	
	// Close the file if it is open.
	if (fRefNum != 0)
		(void) TestAndStoreResult (result, FSClose (fRefNum));
		
	// Delete the file if we had an error.	
	 if (*result != noErr)
		 (void) FSpDelete (&fsSpec);
			
	// Flush the volume anyway.
	if (!TestAndStoreResult (result, FlushVol (NULL, fsSpec.vRefNum))) return FALSE;
	
	// Mark the file as clean.
	*dirty = FALSE;
	
	/* create alias for scripting system */
	
	if (sameNames)
	{ // didn't enter new filename, so set filename to nothing
		fsSpec.name[ (fsSpec.name[0] = 0)+1 ] = 0;
	} // otherwise use filename and store entire reference

	gotErr = NewAlias(nil, &fsSpec, alias);

	return (gotErr == noErr);
}
int dir_Delete(char *pathString, int pathStringLength) {
	/* Delete the existing directory with the given path. */
    char cFileName[1000];

    if (pathStringLength >= 1000) {
        return false;
    }

	if (equalsLastPath(pathString, pathStringLength))
		lastPathValid = false;

#if defined(__MWERKS__)
	{
    	/* Delete the existing directory with the given path. */
        FSSpec spec;
        OSErr  err;

        if ((err = makeFSSpec(pathString, pathStringLength,&spec))  != noErr)
            return false;
            
       	return FSpDelete(&spec) == noErr;
    }
#else
    /* copy the file name into a null-terminated C string */
    sqFilenameFromString(cFileName, (int) pathString, pathStringLength);
    return rmdir(cFileName) == 0;
#endif
}
Ejemplo n.º 3
0
short file_delete(const char *path) {

	FSSpec	fss;
	Str255	fname;

	mkstr255(fname, path);
	FSMakeFSSpec(0, 0, fname, &fss);
	FSpDelete(&fss);
	return(0);
}
int dir_Delete(char *pathString, int pathStringLength) {
	/* Delete the existing directory with the given path. */
    FSSpec spec;
    OSErr  err;

    if ((err = makeFSSpec(pathString, pathStringLength,&spec)) == -1)
        return false;
        
   	return FSpDelete(&spec) == noErr;
}
Ejemplo n.º 5
0
static CWResult LinkHeaders(CWPluginContext context, XPIDLSettings& settings)
{
	// find out how many files there are to link.
	long fileCount = 0;
	CWResult err = CWGetProjectFileCount(context, &fileCount);
	if (err != cwNoErr || fileCount == 0)
		return err;

	// get the output directory.
	FSSpec outputDir;
	err = CWGetOutputFileDirectory(context, &outputDir);
	if (!CWSUCCESS(err))
		return err;
	
	// enumerate all of the output header files, and make aliases to them in
	// the output directory.
	for (long index = 0; (err == cwNoErr) && (index < fileCount); index++) {
		// get the name of each output file.
		CWFileSpec outputFile;
		err = CWGetStoredObjectFileSpec(context, index, &outputFile);
		if (err == cwNoErr) {
			FInfo info;
			err = FSpGetFInfo(&outputFile, &info);
			
			FSSpec aliasFile = { outputDir.vRefNum, outputDir.parID };
			BlockMoveData(outputFile.name, aliasFile.name, 1 + outputFile.name[0]);
			
			AliasHandle alias = NULL;
			if (NewAliasMinimal(&outputFile, &alias) == noErr) {
				// recreate the alias file from scratch.
				FSpDelete(&aliasFile);
				FSpCreateResFile(&aliasFile, info.fdCreator, info.fdType, smRoman);
				short refNum = FSpOpenResFile(&aliasFile, fsRdWrPerm);
				if (refNum != -1) {
					UseResFile(refNum);
					AddResource(Handle(alias), rAliasType, 0, aliasFile.name);
					ReleaseResource(Handle(alias));
					UpdateResFile(refNum);
					CloseResFile(refNum);
				}
				// finally, mark the newly created file as an alias file.
				FSpGetFInfo(&aliasFile, &info);
				info.fdFlags |= kIsAlias;
				FSpSetFInfo(&aliasFile, &info);
			}
		}
	}
	
	// create the target file in the output directory.
	BlockMoveData(settings.output, outputDir.name, 1 + settings.output[0]);
	FILE* outputFile = FSp_fopen(&outputDir, "w");
	if (outputFile != NULL) fclose(outputFile);

	return err;
}
Ejemplo n.º 6
0
void CleanTemp(void)
{
    OSErr   err = noErr;
    short   vRefNum;
    long    dirID;
    FSSpec  viewerFSp;
    XPISpec *xpiList, *currXPI = 0, *nextXPI = 0;
#ifdef MIW_DEBUG
    Boolean isDir = false;
#endif
    
#ifndef MIW_DEBUG
    /* get "viewer" in "Temporary Items" folder */
    ERR_CHECK(FindFolder(kOnSystemDisk, kTemporaryFolderType, kCreateFolder, &vRefNum, &dirID));
    err = FSMakeFSSpec(vRefNum, dirID, kViewerFolder, &viewerFSp);
#else
    /* for DEBUG builds temp is "<currProcessVolume>:Temp NSInstall:" */
    ERR_CHECK(GetCWD(&dirID, &vRefNum));
 	err = FSMakeFSSpec(vRefNum, 0, kTempFolder, &viewerFSp);
	if (err == fnfErr)
	    return; /* no debug temp exists */
	err = FSpGetDirectoryID(&viewerFSp, &dirID, &isDir);
	if (err != noErr || !isDir)
	    return;
    err = FSMakeFSSpec(vRefNum, dirID, kViewerFolder, &viewerFSp);
#endif
    
    /* whack the viewer folder if it exists */
    if (err == noErr)
    {
        ERR_CHECK(DeleteDirectory(viewerFSp.vRefNum, viewerFSp.parID, viewerFSp.name));
    }
    
    /* clean out the zippies (.xpi's) */
    xpiList = (XPISpec *) NewPtrClear(sizeof(XPISpec));
    if (!xpiList)
        return;
    IterateDirectory(vRefNum, dirID, "\p", 1, CheckIfXPI, (void*)&xpiList);
    
    if (xpiList)
    {
        currXPI = xpiList;
        while(currXPI)
        {
            nextXPI = currXPI->next; /* save nextXPI before we blow away currXPI */
            if (currXPI->FSp)
            {
                FSpDelete(currXPI->FSp);
                DisposePtr((Ptr)currXPI->FSp);
            }
            DisposePtr((Ptr)currXPI);
            currXPI = nextXPI;
        }
    }
}
Ejemplo n.º 7
0
ConstStr255Param fname = (ConstStr255Param)"\pxxx-test-resource-xxx";


void test_fspcreateresfile(void)
{
    OSErr err;
    FSSpec spec;

    err = FSMakeFSSpec(0, 0, fname, &spec);
    if (err) {

        fprintf(stderr, "FSMakeFSSpec failed: %d\n", err);
        exit(3);
    }

    FSpDelete(&spec);
    FSpCreateResFile(&spec, 'TEST', 'BINA', 0);
    if ( (err = ResError()) != 0) {
        fprintf(stderr, "FSpCreateResFile failed (File does not exist): %d\n", err);
        exit(1);
    }

    // Verify it doesn't fail if the file/fork already exist.
    FSpCreateResFile(&spec, 'TEST', 'BINA', 0);
    if ( (err = ResError()) != 0) {
        fprintf(stderr, "FSpCreateResFile (File/Fork exist) failed: %d\n", err);
        exit(2);
    }

    // Verify it doesn't fail if the file exists w/o a resource fork.
    FSpDelete(&spec);
    FSpCreate(&spec, 'TEST', 'BINA', 0);
    FSpCreateResFile(&spec, 'TEST', 'BINA', 0);
    if ( (err = ResError()) != 0) {
        fprintf(stderr, "FSpCreateResFile (File exists) failed: %d\n", err);
        exit(2);
    }

    FSpDelete(&spec);


}
Ejemplo n.º 8
0
/*
 * Open a TIFF file for read/writing.
 */
TIFF*
TIFFOpen(const char* name, const char* mode)
{
  static const char module[] = "TIFFOpen";
  Str255 pname;
  FInfo finfo;
  short fref;
  OSErr err;
  FSSpec  fSpec;

  strcpy((char*) pname, name);
  ourc2pstr((char*) pname);
  
  err = FSMakeFSSpec( 0, 0, pname, &fSpec );

  switch (_TIFFgetMode(mode, module)) {
  default:
    return ((TIFF*) 0);
  case O_RDWR | O_CREAT | O_TRUNC:
    if (FSpGetFInfo(&fSpec, &finfo) == noErr)
      FSpDelete(&fSpec);
    /* fall through */
  case O_RDWR | O_CREAT:
    if ((err = FSpGetFInfo(&fSpec, &finfo)) == fnfErr) {
      if (FSpCreate(&fSpec, '    ', 'TIFF', smSystemScript) != noErr)
        goto badCreate;
      if (FSpOpenDF(&fSpec, fsRdWrPerm, &fref) != noErr)
        goto badOpen;
    } else if (err == noErr) {
      if (FSpOpenDF(&fSpec, fsRdWrPerm, &fref) != noErr)
        goto badOpen;
    } else
      goto badOpen;
    break;
  case O_RDONLY:
    if (FSpOpenDF(&fSpec, fsRdPerm, &fref) != noErr)
      goto badOpen;
    break;
  case O_RDWR:
    if (FSpOpenDF(&fSpec, fsRdWrPerm, &fref) != noErr)
      goto badOpen;
    break;
  }
  return (TIFFFdOpen((int) fref, name, mode));
badCreate:
  TIFFErrorExt(0, module, "%s: Cannot create", name);
  return ((TIFF*) 0);
badOpen:
  TIFFErrorExt(0, module, "%s: Cannot open", name);
  return ((TIFF*) 0);
}
Ejemplo n.º 9
0
Boolean PIOpenFile (FSSpec& fsSpec, FileHandle *fRefNum, short *result)
{
	*fRefNum = 0;
	
	if (!TestAndStoreResult (result, FSpOpenDF (&fsSpec, fsCurPerm, fRefNum)))
	{
		FSpDelete (&fsSpec);
		return FALSE;
	}
	else
	{
		return TRUE;
	}	
}
Ejemplo n.º 10
0
OSErr
CleanupExtractedFiles(short tgtVRefNum, long tgtDirID)
{
	OSErr		err = noErr;
	FSSpec		coreDirFSp;
	StringPtr	pcoreDir = nil;
	short		i = 0;
	
	HLock(gControls->cfg->coreDir);
	if (*gControls->cfg->coreDir != NULL && **gControls->cfg->coreDir != NULL)		
	{
		// just need to delete the core dir and its contents
		
		pcoreDir = CToPascal(*gControls->cfg->coreDir);
		err = FSMakeFSSpec(tgtVRefNum, tgtDirID, pcoreDir, &coreDirFSp);
		if (err == noErr)
		{
			err = FSpDelete( &coreDirFSp );
		}
	
		HUnlock(gControls->cfg->coreDir);
		goto aurevoir;
	}	
		
	HUnlock(gControls->cfg->coreDir);
	
	// otherwise iterate through coreFileList deleteing each individually
	for (i=0; i<currCoreFile+1; i++)
	{
		FSpDelete( &coreFileList[i] );
	}

aurevoir:
	if (pcoreDir)
		DisposePtr((Ptr) pcoreDir);	
	return err;
}
Ejemplo n.º 11
0
OSErr
ForceMoveFile(short vRefNum, long parID, ConstStr255Param name, long newDirID)
{
	OSErr 	err = noErr;
	FSSpec 	tmpFSp;
	
	err = CatMove(vRefNum, parID, name, newDirID, nil);
	if (err == dupFNErr)
	{
		// handle for stomping over old file
		err = FSMakeFSSpec(vRefNum, newDirID, name, &tmpFSp);
		err = FSpDelete(&tmpFSp);
		err = CatMove(vRefNum, parID, name, newDirID, nil);
	}
	
	return err;		
}
Ejemplo n.º 12
0
void close_settings_w(void *handle) {
    struct write_settings *ws = handle;
    OSErr error;

    CloseResFile(ws->fd);
    if ((error = ResError()) != noErr)
	goto out;
    error = FSpExchangeFiles(&ws->tmpfile, &ws->dstfile);
    if (error != noErr) goto out;
    error = FSpDelete(&ws->tmpfile);
    if (error != noErr) goto out;
    return;

  out:
    fatalbox("Close of saved session failed (%d)", error);
    safefree(handle);
}
Ejemplo n.º 13
0
void del_settings(char const *sessionname) {
    OSErr error;
    FSSpec sessfile;
    short sessVRefNum;
    long sessDirID;
    Str255 psessionname;

    error = get_session_dir(kDontCreateFolder, &sessVRefNum, &sessDirID);

    c2pstrcpy(psessionname, sessionname);
    error = FSMakeFSSpec(sessVRefNum, sessDirID, psessionname, &sessfile);
    if (error != noErr) goto out;

    error = FSpDelete(&sessfile);
    return;
  out:
    fatalbox("Delete session failed (%d)", error);
}
Ejemplo n.º 14
0
pascal	OSErr	FSpDeleteCompat(const FSSpec *spec)
{
#if !__MACOSSEVENORLATER
    if ( !FSHasFSSpecCalls() && !QTHasFSSpecCalls() )
    {
        HParamBlockRec	pb;

        pb.ioParam.ioVRefNum = spec->vRefNum;
        pb.fileParam.ioDirID = spec->parID;
        pb.ioParam.ioNamePtr = (StringPtr) &(spec->name);
        pb.ioParam.ioVersNum = 0;
        return ( PBHDeleteSync(&pb) );
    }
    else
#endif	/* !__MACOSSEVENORLATER */
    {
        return ( FSpDelete(spec) );
    }
}
Ejemplo n.º 15
0
	static PGPError
sDeleteProc( PFLConstFileSpecRef ref )
{
	PGPError		err	= kPGPError_NoErr;
	MyData *		myData	= GetMyData( ref );
	
	if ( myData->specIsValid )
	{
		err	= FSpDelete( &myData->spec );
		if ( err == fnfErr )
			err	= kPGPError_FileNotFound;
		else if ( IsPGPError( err ) )
			err	= kPGPError_FileOpFailed;
	}
	else
	{
		err	= kPGPError_FileNotFound;
	}
	
	return( err );
}
Ejemplo n.º 16
0
FILEH file_create(const char *path) {

	FILEH	ret;
	FSSpec	fss;
	Str255	fname;
	OSType	creator = kUnknownType;
	OSType	fileType = kUnknownType;

	mkstr255(fname, path);
	FSMakeFSSpec(0, 0, fname, &fss);
	FSpDelete(&fss);

	if (FSpCreate(&fss, creator, fileType, smSystemScript) == noErr) {
		if ((FSpOpenDF(&fss, fsRdPerm | fsWrPerm, &ret) == noErr) ||
			(FSpOpenDF(&fss, fsRdPerm, &ret) == noErr)) {
			SetFPos(ret, fsFromStart, 0);
			return(ret);
		}
	}
	return(-1);
}
Ejemplo n.º 17
0
/* デバッグファイルを作成し、開く */
void CreateDebugFile(void)
{
	OSErr	err;
	FSSpec	spec;
	ProcessSerialNumber	psn;
	ProcessInfoRec		processInfo;
	
	/* アプリケーションの位置を記録 */
	err=GetCurrentProcess(&psn);
	processInfo.processInfoLength=sizeof(ProcessInfoRec);
	processInfo.processName=nil;
	processInfo.processAppSpec=&spec;
	err=GetProcessInformation(&psn,&processInfo);
	
	if (err!=noErr) return;
	
	PStrCpy(kDebugFileName,spec.name);
	
	#ifdef BACKUP_LOG
	{
		/* バックアップする */
		FSSpec	bSpec=spec;
		PStrCpy(kBDebugFileName,bSpec.name);
		
		err=FSpCreate(&bSpec,kDebugFileCreator,kDebugFileType,smSystemScript);
		
		err=FSpExchangeFiles(&spec,&bSpec);
	}
	#endif
	
	/* まず消す */
	err=FSpDelete(&spec);
	
	err=FSpCreate(&spec,kDebugFileCreator,kDebugFileType,smSystemScript);
	if (err!=noErr) return;
	
	err=FSpOpenDF(&spec,fsWrPerm,&debugFileRefNum);
	if (err!=noErr) return;
}
Ejemplo n.º 18
0
/*
 * NB: Destination file must exist.
 */
void *open_settings_w_fsp(FSSpec *dstfile)
{
    short tmpVRefNum;
    long tmpDirID;
    struct write_settings *ws;
    OSErr error;
    Str255 tmpname;

    ws = snew(struct write_settings);
    ws->dstfile = *dstfile;

    /* Create a temporary file to save to first. */
    error = FindFolder(ws->dstfile.vRefNum, kTemporaryFolderType,
		       kCreateFolder, &tmpVRefNum, &tmpDirID);
    if (error != noErr) goto out;
    c2pstrcpy(tmpname, tmpnam(NULL));
    error = FSMakeFSSpec(tmpVRefNum, tmpDirID, tmpname, &ws->tmpfile);
    if (error != noErr && error != fnfErr) goto out;
    if (error == noErr) {
	error = FSpDelete(&ws->tmpfile);
	if (error != noErr) goto out;
    }
    FSpCreateResFile(&ws->tmpfile, PUTTY_CREATOR, SESS_TYPE, smSystemScript);
    if ((error = ResError()) != noErr) goto out;

    ws->fd = FSpOpenResFile(&ws->tmpfile, fsWrPerm);
    if (ws->fd == -1) {error = ResError(); goto out;}

    /* Set up standard resources.  Doesn't matter if these fail. */
    copy_resource('STR ', -16396);
    copy_resource('TMPL', TMPL_Int);

    return ws;

  out:
    safefree(ws);
    fatalbox("Failed to open session for write (%d)", error);
}
Ejemplo n.º 19
0
int destroy(char *path)
{
static char lastpath[NAME_MAX];
static FSSpec  trashfolder;
static Boolean FirstCall = true;
static char Num = 0;
static Boolean  Immediate_File_Deletion = false;
char    currpath[NAME_MAX], *envptr;
FSSpec  fileToDelete;
OSErr   err;

/* init this function */
if ((path == NULL) ||
    (strlen(path) == 0))
    {
    FirstCall = true;
    Num = 0;
    return -1;
    }

UserStop();

RfDfFilen2Real(currpath, path, MacZip.MacZipMode,
                MacZip.DataForkOnly, &MacZip.CurrentFork);
GetCompletePath(currpath,currpath,&fileToDelete, &err);

if (FirstCall == true)
    {
    FirstCall = false;
    sstrcpy(lastpath,currpath);
    err = FSpFindFolder(fileToDelete.vRefNum, kTrashFolderType,
                      kDontCreateFolder,&trashfolder);
    printerr("FSpFindFolder:",err,err,__LINE__,__FILE__,path);

    envptr = getenv("Immediate_File_Deletion");
    if (!(envptr == (char *)NULL || *envptr == '\0'))
        {
        if (stricmp(envptr,"yes") == 0)
            Immediate_File_Deletion = true;
        else
            Immediate_File_Deletion = false;
        }

    if (Immediate_File_Deletion)
        {
        err = FSpDelete(&fileToDelete);
        return err;
        }

    err = CatMove (fileToDelete.vRefNum, fileToDelete.parID,
                   fileToDelete.name, trashfolder.parID, trashfolder.name);
    return err;
    }

if (strcmp(currpath,lastpath) == 0)
    {
    return 0; /* ignore, file is already deleted */
    }
else
    {

    if (Immediate_File_Deletion)
        {
        err = FSpDelete(&fileToDelete);
        sstrcpy(lastpath,path);
        return err;
        }

    err = CatMove (fileToDelete.vRefNum, fileToDelete.parID,
                   fileToDelete.name, trashfolder.parID, trashfolder.name);

    /* -48 = file is already existing so we have to rename it before
       moving the file */
    if (err == -48)
        {
        Num++;
        if (fileToDelete.name[0] >= 28) /* cut filename if to long */
            fileToDelete.name[0] = 28;
        P2CStr(fileToDelete.name);
        sprintf(currpath,"%s~%d",(char *)fileToDelete.name,Num);
        C2PStr(currpath);
        C2PStr((char *)fileToDelete.name);
        err = HRename (fileToDelete.vRefNum, fileToDelete.parID,
                       fileToDelete.name, (unsigned char *) currpath);
        err = CatMove (fileToDelete.vRefNum, fileToDelete.parID,
                       (unsigned char *) currpath, trashfolder.parID,
                       trashfolder.name);
        }
    }

sstrcpy(lastpath,currpath);
return err;
}
Ejemplo n.º 20
0
close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
{
  FSClose ( info->temp_file );
  FSpDelete ( &(info->tempSpec) );
}
Ejemplo n.º 21
0
OSErr QTDR_CopyRemoteFileToLocalFile (char *theURL, FSSpecPtr theFile)
{
	Handle				myReaderRef = NULL;			// data reference for the remote file
	Handle				myWriterRef = NULL;			// data reference for the local file
	ComponentResult		myErr = badComponentType;

	//////////
	//
	// create the local file with the desired type and creator
	//
	//////////
	
	// delete the target local file, if it already exists;
	// if it doesn't exist yet, we'll get an error (fnfErr), which we just ignore
	FSpDelete(theFile);
	
	myErr = FSpCreate(theFile, kTransFileCreator, kTransFileType, smSystemScript);
	if (myErr != noErr)
		goto bail;
	
	//////////
	//
	// create data references for the remote file and the local file
	//
	//////////
	
	myReaderRef = QTDR_MakeURLDataRef(theURL);
    if (myReaderRef == NULL)
    	goto bail;

	myWriterRef = QTDR_MakeFileDataRef(theFile);
    if (myWriterRef == NULL)
    	goto bail;

	//////////
	//
	// find and open the URL and file data handlers; connect the data references to them
	//
	//////////
	
	gDataReader = OpenComponent(GetDataHandler(myReaderRef, URLDataHandlerSubType, kDataHCanRead));
	if (gDataReader == NULL)
		goto bail;

	gDataWriter = OpenComponent(GetDataHandler(myWriterRef, rAliasType, kDataHCanWrite));
	if (gDataWriter == NULL)
		goto bail;
		
	// set the data reference for the URL data handler
	myErr = DataHSetDataRef(gDataReader, myReaderRef);
	if (myErr != noErr)
		goto bail;
	
	// set the data reference for the file data handler
	myErr = DataHSetDataRef(gDataWriter, myWriterRef);
	if (myErr != noErr)
		goto bail;
	
	//////////
	//
	// allocate a data buffer; the URL data handler copies data into this buffer,
	// and the file data handler copies data out of it
	//
	//////////
	
	gDataBuffer = NewPtrClear(kDataBufferSize);
	myErr = MemError();
	if (myErr != noErr)
		goto bail;
		
	//////////
	//
	// connect to the remote and local files
	//
	//////////
	
	// open a read-only path to the remote data reference
	myErr = DataHOpenForRead(gDataReader);
	if (myErr != noErr)
		goto bail;

	// get the size of the remote file
	myErr = DataHGetFileSize(gDataReader, &gBytesToTransfer); 
	if (myErr != noErr)
		goto bail;
	
	// open a write-only path to the local data reference
	myErr = DataHOpenForWrite(gDataWriter);
	if (myErr != noErr)
		goto bail;
		
	//////////
	//
	// start reading and writing data
	//
	//////////
	
	gDoneTransferring = false;
	gBytesTransferred = 0L;
	
	gReadDataHCompletionUPP = NewDataHCompletionUPP(QTDR_ReadDataCompletionProc);
	gWriteDataHCompletionUPP = NewDataHCompletionUPP(QTDR_WriteDataCompletionProc);
		
	// start retrieving the data; we do this by calling our own write completion routine,
	// pretending that we've just successfully finished writing 0 bytes of data
	QTDR_WriteDataCompletionProc(gDataBuffer, 0L, noErr);

bail:
	// if we encountered any error, close the data handler components
	if (myErr != noErr)
		QTDR_CloseDownHandlers();
	
	return((OSErr)myErr);
}
Ejemplo n.º 22
0
void
XMLMacCarbonFile::create(const XMLCh* const filePath)
{
    OSErr err = noErr;

    //	Split path into directory and filename components
    int posSlash = XMLString::lastIndexOf(filePath, '/', XMLString::stringLen(filePath) - 1);
    int posName = (posSlash == -1) ? 0 : posSlash+1;

    const XMLCh* namePtr = filePath + posName;
    int nameLen = XMLString::stringLen(namePtr);

    //	Make a temporary string of the directory
    ArrayJanitor<XMLCh> dirPath(new XMLCh[namePtr - filePath + 1]);
    XMLString::subString(dirPath.get(), filePath, 0, posName);

    //	Create the file as appropriate for API set
    if (gHasHFSPlusAPIs)
    {
    	//	HFS+
        FSRef ref;

        //	If we find an existing file, delete it
        if (XMLParsePathToFSRef(filePath, ref))
            FSDeleteObject(&ref);

        //	Get a ref to the parent directory
        if (!XMLParsePathToFSRef(dirPath.get(), ref))
            err = fnfErr;

        //	Create a new file using the unicode name
        if (err == noErr)
        {
            UniChar uniName[256];
            err = FSCreateFileUnicode(
                    &ref,
                    nameLen, CopyXMLChsToUniChars(namePtr, uniName, nameLen, sizeof(uniName)),
                    0, NULL, NULL, NULL);
        }
    }
    else
    {
    	//	HFS
        FSSpec spec;

        //	If we find an existing file, delete it
        if (XMLParsePathToFSSpec(filePath, spec))
            FSpDelete(&spec);

        //	Get a spec to the parent directory
        if (!XMLParsePathToFSSpec(dirPath.get(), spec))
            err = fnfErr;

        //	Check that the new name is not too long for HFS
        if (err == noErr && nameLen > 31)
            err = errFSNameTooLong;

        if (err == noErr)
        {
            //	Transcode the unicode name to native encoding
            ArrayJanitor<const char> nativeName(XMLString::transcode(namePtr));

            // Make a partial pathname from our current spec (parent directory) to the new file
            unsigned char name[31 * 2 + 1 * 2 + 1];
            unsigned char* partial = &name[1];

            *partial++ = ':';      			 // Partial leads with :
            const unsigned char* specName = spec.name;	// Copy in spec name
            for (int specCnt = *specName++; specCnt > 0; --specCnt)
                *partial++ = *specName++;

            *partial++ = ':';      			 // Path component separator
            char c;
            for (const char* p = nativeName.get(); (c = *p++) != 0; ) // Copy in new element
                *partial++ = (c == ':') ? '/' : c;		// Convert : to /

            name[0] = partial - &name[1];   // Set the pascal string name length

            //	Update the spec: this will probably return fnfErr
            //					 (since we just deleted any existing file)
            err = FSMakeFSSpec(spec.vRefNum, spec.parID, name, &spec);

            //	Create the file from the spec
            err = FSpCreate(&spec, '??\??', 'TEXT', smSystemScript);
        }
    }

    //	Fail if we didn't create the file
    if (err != noErr)
    {
        ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotReadFromFile);
        //ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile);
    }
}
Ejemplo n.º 23
0
static OSErr mainQTInst(void					*unused,
						OSType					order,				// Order to execute
						InstrData				*InsHeader,			// Ptr on instrument header
						sData					**sample,			// Ptr on samples data
						short					*sampleID,			// If you need to replace/add only a sample, not replace the entire instrument (by example for 'AIFF' sound)
																	// If sampleID == -1 : add sample else replace selected sample.
						CFURLRef				AlienFileURLRef,	// IN/OUT file
						PPInfoPlug				*thePPInfoPlug)
{
	MADErr		myErr = MADNoErr;
	FSIORefNum	iFileRefI = -1;
	ByteCount	inOutBytes;
	FSSpec		tmpSpec;
	OSErr		QTErr = noErr;
	
	myErr = CFURLToFSSpec(AlienFileURLRef, &tmpSpec);
	switch (myErr) {
		case memFullErr:
			return MADNeedMemory;
			break;
			
		default:
		case fnfErr:
			return order == MADPlugExport ? MADWritingErr : MADReadingErr;
			break;
						
		case noErr:
			break;
	}
	
	switch (order) {
		case MADPlugPlay:
			break;
			
		case MADPlugImport:
		{
			Ptr				theSound;
			int				lS, lE;
			short			sS;
			unsigned long	rate;
			bool			stereo;
			FSSpec			newFile;
			
			myErr = ConvertDataToWAVE(tmpSpec, &newFile, thePPInfoPlug);
			if (myErr == noErr) {
				theSound = ConvertWAV(&newFile, &lS, &lE, &sS, &rate, &stereo);
				
				if (theSound) {
					long sndSize = GetPtrSize(theSound);
					Ptr newSound = malloc(sndSize);
					memcpy(newSound, theSound, sndSize);
					DisposePtr(theSound);
					myErr = inAddSoundToMAD(newSound, sndSize, lS, lE, sS, 60, rate, stereo, newFile.name, InsHeader, sample, sampleID);
				} else {
					myErr = MADNeedMemory;
				}
				
				FSpDelete(&newFile);
			}
		}
			break;
			
		case MADPlugTest:
		{
			Boolean canOpenAsMovie = false;
			FInfo fInfo;
			
			FSpGetFInfo(&tmpSpec, &fInfo);
			QTErr = CanQuickTimeOpenFile(&tmpSpec, fInfo.fdType, 0, NULL, &canOpenAsMovie, NULL, 0);
			if (QTErr == noErr && canOpenAsMovie == true) {
				myErr = MADNoErr;
			} else {
				myErr = MADIncompatibleFile;
			}
		}
			break;
			
		case MADPlugExport:
			if (*sampleID >= 0) {
				OSType			compType = 'NONE';
				unsigned long	rate;
				sData 			*curData = sample[*sampleID];
				short			numChan;
				
				FSpDelete(&tmpSpec);
				myErr = FSpCreate(&tmpSpec, 'TVOD', 'AIFF', smCurrentScript);
				if(myErr == noErr)
					myErr = FSpOpenDF(&tmpSpec, fsCurPerm, &iFileRefI);
				
				if (myErr == noErr) {
					inOutBytes 	= curData->size;
					rate		= curData->c2spd;
					
					if (curData->stereo)
						numChan = 2;
					else
						numChan = 1;
					
					myErr = SetupAIFFHeader(iFileRefI, numChan, rate << 16L, curData->amp, compType, inOutBytes, 0);
					
					if(myErr == noErr)
						myErr = FSWriteFork(iFileRefI, fsAtMark, 0, inOutBytes, curData->data, &inOutBytes);
					FSCloseFork(iFileRefI);
				}
			}
			break;
			
		default:
			myErr = MADOrderNotImplemented;
			break;
	}
	
	return myErr;
}
Ejemplo n.º 24
0
static OSStatus DoFSRefSave(const OurSaveDialogData *dialogDataP, 
                                    NavReplyRecord* reply, AEDesc *actualDescP)
{
    OSStatus 	err = noErr;
    FSRef 	fileRefParent;
	    
    if ((err = AEGetDescData( actualDescP, &fileRefParent, sizeof( FSRef ) )) == noErr )
    {
        // get the name data and its length:	
        HFSUniStr255	nameBuffer;
        UniCharCount 	sourceLength = 0;
        
        sourceLength = (UniCharCount)CFStringGetLength( reply->saveFileName );
        
        CFStringGetCharacters( reply->saveFileName, CFRangeMake( 0, sourceLength ), 
                                                        (UniChar*)&nameBuffer.unicode );
        
        if ( sourceLength > 0 )
        {	
            if ( reply->replacing )
            {
                // delete the file we are replacing:
                FSRef fileToDelete;
                if ((err = FSMakeFSRefUnicode( &fileRefParent, sourceLength, nameBuffer.unicode, 
                                    kTextEncodingUnicodeDefault, &fileToDelete )) == noErr )
                {
                    err = FSDeleteObject( &fileToDelete );
                    if ( err == fBsyErr ){
                        DoErrorAlert(fBsyErr, kMyDeleteErrorFormatStrKey);
                    }
                }
            }
                            
            if ( err == noErr )
            {
                // create the file based on Unicode, but we can write the file's data with an FSSpec:
                FSSpec newFileSpec;

                // get the FSSpec back so we can write the file's data
                if ((err = FSCreateFileUnicode( &fileRefParent, sourceLength, 
                                                    nameBuffer.unicode,
                                                    kFSCatInfoNone,
                                                    NULL,
                                                    NULL,	
                                                    &newFileSpec)) == noErr)
                {
                    FInfo fileInfo;
                    fileInfo.fdType = kFileTypePDF;
                    fileInfo.fdCreator = kFileCreator;
                    err = FSpSetFInfo( &newFileSpec, &fileInfo );
                    // now that we have the FSSpec, we can proceed with the save operation:
                    if(!err){
                        FSRef fsRef;
                        err = FSpMakeFSRef(&newFileSpec, &fsRef);	// make an FSRef
                        if(!err){
                            CFURLRef saveURL = CFURLCreateFromFSRef(NULL, &fsRef);
                            if(saveURL){
                                // delete the file we just made for making the FSRef
                                err = FSpDelete(&newFileSpec);	
                                if(!err)
                                    err = MakePDFDocument(dialogDataP->parentWindow, 
                                                            dialogDataP->documentDataP, 
                                                            saveURL);
                                if(!err)
                                    err = NavCompleteSave( reply, kNavTranslateInPlace );
                                
                                if(err){
                                    // an error ocurred saving the file, so delete the copy 
                                    // left over:
                                    (void)FSpDelete( &newFileSpec );
                                    DoErrorAlert(err, kMyWriteErrorFormatStrKey);
                                }
                                CFRelease(saveURL);
                            }else{
                                // delete the file we just made for making the FSRe
                               (void)FSpDelete(&newFileSpec);
                                err = kCantCreateSaveURL;
                                DoErrorAlert(err, kMyCreateURLErrorFormatStrKey);
                            }
                        }
                    }
                }
            }
        }
    }
    return err;
}
Ejemplo n.º 25
0
void saveToPICTFile()
{

/*
Saving a PixMap as a PICT file isn't too hard.

1.  Open a Picture with the port set to the destination of #2.
2.  CopyBits the PixMap onto itself or another port.  (Because CopyBits is
recorded in Pictures.
3.  Close the picture.
4.  Open the data fork for the file.
5.  Write out 512 bytes of zeros followed by the contents of the Picture
handle.
6.  Close the file.
*/

	PicHandle			picHandle;
	OSErr				anErr = noErr;
	OSType              fileTypeToSave = 'PICT';
    OSType              creatorType = 'ogle';
    NavReplyRecord      reply;
    NavDialogOptions    dialogOptions;
    FSSpec      		documentFSSpec;
    long				inOutCount;
    short				refNum, count;
    AEKeyword   		theKeyword;
    DescType    		actualType;
	unsigned char 		header[512];
	Size        		actualSize;
	Rect				tempRect1;
	
	CopyBits(GetPortBitMapForCopyBits(GetWindowPort(FrontWindow())), (BitMap*) &gPixMap, 
	 GetPortBounds(GetWindowPort(gWindow), &tempRect1), &gPixMap.bounds, srcCopy, 0L);
	
	SetPortWindowPort(gWindow);
	
	picHandle = OpenPicture(&gPixMap.bounds);
	
	CopyBits((BitMap*) &gPixMap, GetPortBitMapForCopyBits(GetWindowPort(FrontWindow())), &gPixMap.bounds, 
	 GetPortBounds(GetWindowPort(gWindow), &tempRect1), srcCopy, 0L);
	 
	ClosePicture();

    for (count = 0; count < 512; count++)
		header[count] = 0x00;

    anErr = NavGetDefaultDialogOptions(&dialogOptions); 
    dialogOptions.dialogOptionFlags |= kNavSelectDefaultLocation;
    
    anErr = NavPutFile( nil, 
    					&reply, 
    					&dialogOptions, 
    					nil,
                        fileTypeToSave, 
                        creatorType, 
                        nil );

	if (anErr == noErr && reply.validRecord) {
		anErr = AEGetNthPtr(&(reply.selection), 1, typeFSS,
                                &theKeyword, &actualType,
                                &documentFSSpec, sizeof(documentFSSpec),
                                &actualSize );
    if (anErr == noErr) {
  	  
  	  		anErr = FSpCreate(&documentFSSpec, creatorType, fileTypeToSave, smSystemScript);
			if (anErr == dupFNErr) {
				anErr = FSpDelete(&documentFSSpec);
				anErr = FSpCreate(&documentFSSpec, creatorType, fileTypeToSave, smSystemScript);
			}		// this is quick 'n' dirty or there'd be more robust handling here
			
    		// write the file
    		FSpOpenDF(&documentFSSpec, fsRdWrPerm, &refNum );
    		inOutCount = 512;
   			anErr = FSWrite(refNum, &inOutCount, header);		// write the header
    		if (anErr == noErr) {
    			inOutCount = GetHandleSize((Handle)picHandle);
				anErr = FSWrite(refNum,&inOutCount,*picHandle);
    		}
    		FSClose( refNum );
  	  }
  	  reply.translationNeeded = false;
  	  anErr = NavCompleteSave(&reply, kNavTranslateInPlace);
    
 	  NavDisposeReply(&reply);
    }
	
	KillPicture(picHandle);
}
Ejemplo n.º 26
0
OSErr PAS_DecodeFile(FSSpec *inSpec, FSSpec *outSpec)
{
	OSErr		err;
	short		inRefNum;
	
	PASHeader	header;
	
	PASEntry 	dataEntry, miscEntry, resourceEntry;
	long		sizeOfEntry;

	if (inSpec == NULL || outSpec == NULL)
		return paramErr;
		
		
	FSpDelete( outSpec ) ;
	
	err = FSpCreate( outSpec, kCreator, kType ,smSystemScript );
	
	if (err != noErr) 	return err;
	
	
	
	err = FSpOpenDF(inSpec, fsRdPerm, &inRefNum);
	
	if (err != noErr)  goto error;

	
	/* Read Header */
		
	err	= PAS_decodeHeader(inRefNum, &header);
	if (err != noErr)  goto error;
	
	if(	header.magicNum != PAS_MAGIC_NUM ||
		header.versionNum != PAS_VERSION)
	{
		err = -1;
		goto error;
	}
	
	
	
	/* Read Data Entry */
	
	
	err = SetFPos(inRefNum, fsFromStart, sizeof(PASHeader));
	if (err != noErr) 	goto error;
	
	sizeOfEntry			=	sizeof(PASEntry);

	err = FSRead(inRefNum, &sizeOfEntry, &dataEntry);
	if (err != noErr) 	goto error;
	
	
	
	
	/* Read Misc Entry */
	
	
	err = SetFPos(inRefNum, fsFromStart, (sizeof(PASHeader) + sizeof(PASEntry)));
	if (err != noErr) 	goto error;
	
	sizeOfEntry			=	sizeof(PASEntry);

	err = FSRead(inRefNum, &sizeOfEntry, &miscEntry);
	if (err != noErr) 	goto error;
	

	/* Read Resource Entry */
	
	
	err = SetFPos(inRefNum, fsFromStart, (sizeof(PASHeader) + (2 * sizeof(PASEntry)))) ;
	if (err != noErr) 	goto error;
	
	sizeOfEntry			=	sizeof(PASEntry);

	err = FSRead(inRefNum, &sizeOfEntry, &resourceEntry);
	if (err != noErr) 	goto error;





	err =  PAS_decodeData(&dataEntry, outSpec, inRefNum);	
	if (err != noErr) 	goto error;

	err =  PAS_decodeMisc(&miscEntry, outSpec, inRefNum);
	if (err != noErr) 	goto error;

	err =  PAS_decodeResource(&resourceEntry, outSpec, inRefNum);	
	if (err == kResFileNotOpened)
	{
		// there was no resource fork
		err = noErr;
	}
	else if (err != noErr)
	{
		goto error;
	}

	
	FSClose(inRefNum);
	
	return noErr;
	
	
	
error:

	if (inRefNum != kResFileNotOpened)
	{
		FSClose(inRefNum);
	}
		
	FSpDelete( outSpec ) ;
	
	return err;
	
}
Ejemplo n.º 27
0
OSErr
InflateFiles(void *hZip, void *hFind, short tgtVRefNum, long tgtDirID)
{
	OSErr		err = noErr;
	Boolean		bFoundAll = false;
	PRInt32		rv = 0;
	char		filename[255] = "\0", *lastslash, *leaf, macfilename[255] = "\0";
	Handle		fullPathH = 0;
	short 		fullPathLen = 0;
	Ptr			fullPathStr = 0;
	StringPtr	extractedFile = 0;
	FSSpec		extractedFSp, outFSp;
	
	
	while (!bFoundAll)
	{
		/* find next item if one exists */
		rv = ZIP_FindNext( hFind, filename, 255 );
		if (rv==ZIP_ERR_FNF)
		{
			bFoundAll = true;
			break;
		}
		else if (rv!=ZIP_OK)
			return rv;	
		
		/* ignore if item is a dir entry */	
		lastslash = strrchr(filename, '/');
		if (lastslash == (&filename[0] + strlen(filename) - 1)) /* dir entry encountered */
			continue;

		/* grab leaf filename only */
		if (lastslash == 0)
			leaf = filename;
		else
			leaf = lastslash + 1;
		
		/* obtain and NULL terminate the full path string */
		err = GetFullPath(tgtVRefNum, tgtDirID, "\p", &fullPathLen, &fullPathH); /* get dirpath */
		if (err!=noErr)
			return err;

        strcpy(macfilename, filename);        
        SLASHES_2_COLONS(macfilename);
		HLock(fullPathH);
		fullPathStr = NewPtrClear(fullPathLen + strlen(macfilename) + 1);
		strncat(fullPathStr, *fullPathH, fullPathLen);
		strcat(fullPathStr, macfilename);	/* tack on filename to dirpath */
		*(fullPathStr+fullPathLen+strlen(macfilename)) = '\0';
		
		/* create directories if file is nested in new subdirs */
		WhackDirectories(fullPathStr);
		err = DirCreateRecursive(fullPathStr);			
		
		if (err!=noErr)
		{
			if (fullPathStr) 
				DisposePtr((Ptr)fullPathStr);
			if (fullPathH)
			{
				HUnlock(fullPathH);				
				DisposeHandle(fullPathH);
			}
			continue; /* XXX do we want to do this? */
		}
		
		/* extract the file to its full path destination */
		rv = ZIP_ExtractFile( hZip, filename, fullPathStr );
		
		HUnlock(fullPathH);
		if (fullPathH)
			DisposeHandle(fullPathH);
		if (rv!=ZIP_OK)
		{
			if (fullPathStr)
				DisposePtr((Ptr)fullPathStr);			
			return rv;
		}
		
		/* AppleSingle decode if need be */
		extractedFile = CToPascal(fullPathStr); 
		if (extractedFile)
		{
			err = FSMakeFSSpec(0, 0, extractedFile, &extractedFSp);
			err = FSMakeFSSpec(0, 0, extractedFile, &outFSp);
			err = AppleSingleDecode(&extractedFSp, &outFSp);
			
			/* delete original file if named different than final file */
			if (!pstrcmp(extractedFSp.name, outFSp.name))
			{
				err = FSpDelete(&extractedFSp);
			}
		}
			
		/* record for cleanup later */
		FSMakeFSSpec(outFSp.vRefNum, outFSp.parID, outFSp.name, &coreFileList[currCoreFile]);
		currCoreFile++;
		
		/* progress bar update (roll the barber poll) */
		if (gWPtr)
			IdleControls(gWPtr);	
			
		if (extractedFile)
			DisposePtr((Ptr)extractedFile);
		if (fullPathStr)
			DisposePtr(fullPathStr);
	}
        
	return err;
}
Ejemplo n.º 28
0
OSErr PAS_EncodeFile(FSSpec *inSpec, FSSpec *outSpec)
{
	OSErr		err;
	short		outRefNum;
	
	PASEntry 	dataEntry, miscEntry, resourceEntry;
	long		sizeOfEntry;


	if (inSpec == NULL || outSpec == NULL)
		return paramErr;
		

	memset(&dataEntry, 0, sizeof(PASEntry));
	memset(&miscEntry, 0, sizeof(PASEntry));
	memset(&resourceEntry, 0, sizeof(PASEntry));
	
	FSpDelete( outSpec ) ;
	
	err = FSpCreate( outSpec, kCreator, kType ,smSystemScript );
	
	if (err != noErr) 	return err;
	
	
	err = FSpOpenDF(outSpec, fsRdWrPerm, &outRefNum);
	
	if (err != noErr)  goto error;
	

	/* Write Out Header */
		
	err = PAS_encodeHeader(outRefNum);
	if (err != noErr)  goto error;
	
	/* Why am I using three (3)?
		
		E stand for entry.
		
	   The data for the entry is after the THREE headers 
	
		|---------|----|----|----|---------------------->
		   header    E    E    E
	
	*/
	
	
	/* Write Out Data Entry */
	dataEntry.entryID		=	ePas_Data;
	dataEntry.entryLength	=	PAS_getDataSize(inSpec);
	dataEntry.entryOffset	=	sizeof(PASHeader) + (3 * sizeof(PASEntry));
	
	sizeOfEntry			=	sizeof(PASEntry);
	if(dataEntry.entryLength < 0)
	{
		err	= dataEntry.entryLength;
		goto error;
	}
	
	err = FSWrite(outRefNum, &sizeOfEntry, &dataEntry);
	if (err != noErr) 	goto error;
	
	
	
	/* Write Out Misc Entry */
	miscEntry.entryID		=	ePas_Misc;
	miscEntry.entryLength	=	sizeof(PASMiscInfo);
	miscEntry.entryOffset	=	sizeof(PASHeader) + (3 * sizeof(PASEntry)) + dataEntry.entryLength;

	sizeOfEntry			=	sizeof(PASEntry);
	err = FSWrite(outRefNum, &sizeOfEntry, &miscEntry);
	if (err != noErr) 	goto error;
	
	
	/* Write Out Resource Entry */
	resourceEntry.entryID		=	ePas_Resource;
	resourceEntry.entryLength	=	-1;
	resourceEntry.entryOffset	=	sizeof(PASHeader) + (3 * sizeof(PASEntry)) + dataEntry.entryLength + miscEntry.entryLength;


	sizeOfEntry			=	sizeof(PASEntry);
	err = FSWrite(outRefNum, &sizeOfEntry, &resourceEntry);
	if (err != noErr) 	goto error;
	
	err =  PAS_encodeData(inSpec, outRefNum);	
	if (err != noErr) 	goto error;
	
	
	err =  PAS_encodeMisc(inSpec, outRefNum);	
	if (err != noErr) 	goto error;
	
	err =  PAS_encodeResource(inSpec, outRefNum);	
	
	if (err == kResFileNotOpened)
	{
		// there was no resource fork
		err = noErr;
	}
	else if (err != noErr)
	{
		goto error;
	}
		
	FSClose(outRefNum);
	
	return noErr;
	
	
	
error:
		
		
	if (outRefNum != kResFileNotOpened)
	{
		FSClose(outRefNum);
	}
		
	FSpDelete( outSpec ) ;
	 
	return err;

}
Ejemplo n.º 29
0
static MADErr mainAIFF(void *unused, OSType order, InstrData *InsHeader, sData **sample, short *sampleID, CFURLRef AlienFileURL, PPInfoPlug *thePPInfoPlug)
{
	MADErr	myErr = MADNoErr;
	//char	*AlienFile;

	
	switch(order) {
#if 0
		case 'IMPL':
		{
			char			*theSound;
			long			lS, lE;
			short			sS;
			unsigned long	rate;
			Boolean			stereo;
			FSSpec			newFile;
			
			myErr = ConvertDataToWAVE(*AlienFileFSSpec, &newFile, thePPInfoPlug);
			if (myErr == MADNoErr) {
				theSound = ConvertWAV(&newFile, &lS, &lE, &sS, &rate, &stereo);
				
				if (theSound)
					myErr = inAddSoundToMAD(theSound, lS, lE, sS, 60, rate, stereo, AlienFileFSSpec->name, InsHeader, sample, sampleID);
				else
					myErr = MADNeedMemory;
				
				FSpDelete(&newFile);
			}
		}
			break;
#endif
		case MADPlugImport:
		{
			AudioFileID theInID;
			OSStatus myStat = AudioFileOpenURL(AlienFileURL, kAudioFileReadPermission, 0, &theInID);
			if (myStat != noErr) {
				myErr = MADReadingErr;
			} else {
				AudioFileClose(theInID);
				myErr = MADOrderNotImplemented;
			}
		}
			
		case MADPlugTest:
		{
			AudioFileID audioFile;
			OSStatus res;

			res = AudioFileOpenURL(AlienFileURL, kAudioFileReadPermission, kAudioFileAIFFType, &audioFile);
			if (res != noErr) {
				res = AudioFileOpenURL(AlienFileURL, kAudioFileReadPermission, kAudioFileAIFCType, &audioFile);
				if (res != noErr) {
					myErr = MADFileNotSupportedByThisPlug;
				} else {
					AudioFileClose(audioFile);
				}
			} else {
				AudioFileClose(audioFile);
			}
		}
			break;
			
		case MADPlugExport:
			if (*sampleID >= 0)
			{
				char* data = NULL;
				sData *curData = sample[*sampleID];
				AudioStreamBasicDescription asbd = {0};
				asbd.mSampleRate = curData->c2spd;
				asbd.mFormatID = kAudioFormatLinearPCM;
				asbd.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagIsBigEndian;
				asbd.mBitsPerChannel = curData->amp;
				asbd.mChannelsPerFrame = curData->stereo ? 2 : 1;
				asbd.mFramesPerPacket = 1;
				asbd.mBytesPerFrame = asbd.mBitsPerChannel * asbd.mChannelsPerFrame / 8;
				asbd.mBytesPerPacket = asbd.mBytesPerFrame * asbd.mFramesPerPacket;
				
				AudioFileID audioFile;
				OSStatus res;
				if (curData->amp == 16) {
					data = malloc(curData->size);
					if (!data)
						return MADNeedMemory;
					memcpy(data, curData->data, curData->size);
					
					dispatch_apply(curData->size / 2, dispatch_get_global_queue(0, 0), ^(size_t i) {
						PPBE16(&((short*)data)[i]);
					});