extern char* vr_findVerRegName() { FSSpec regSpec; OSErr err; short foundVRefNum; long foundDirID; int bCreate = 0; /* quick exit if we have the info */ if ( verRegName != NULL ) return verRegName; err = FindFolder(kOnSystemDisk,'pref', false, &foundVRefNum, &foundDirID); if (err == noErr) { err = FSMakeFSSpec(foundVRefNum, foundDirID, MAC_VERREG, ®Spec); if (err == -43) /* if file doesn't exist */ { err = FSpCreate(®Spec, 'MOSS', 'REGS', smSystemScript); bCreate = 1; } if (err == noErr) { Handle thePath; short pathLen; err = FSpGetFullPath(®Spec, &pathLen, &thePath); if (err == noErr && thePath) { /* we have no idea if this moves memory, so better lock the handle */ #if defined(STANDALONE_REGISTRY) || defined(USE_STDIO_MODES) HLock(thePath); verRegName = (char *)XP_ALLOC(pathLen + 1); XP_STRNCPY(verRegName, *thePath, pathLen); verRegName[pathLen] = '\0'; #else /* Since we're now using NSPR, this HAS to be a unix path! */ const char* src; char* dst; HLock(thePath); verRegName = (char*)XP_ALLOC(pathLen + 2); src = *(char**)thePath; dst = verRegName; *dst++ = '/'; while (pathLen--) { char c = *src++; *dst++ = (c == ':') ? '/' : c; } *dst = '\0'; #endif } DisposeHandle(thePath); } } return verRegName; }
/*__________________________________________________________________________*/ Boolean SaveDriverState (short refnum, StringPtr file, OSType creator, OSType type) { FSSpec spec; OSErr err; TDriverInfos dInfos; long size, dirID; short vrefNum, ref; Ptr ptr; if (FindMidiShareFolder (true, &vrefNum, &dirID) != noErr) return false; if (!MidiGetDriverInfos (refnum, &dInfos)) return false; size = Get1DriverStateSize (dInfos.slots); if (!size) return true; ptr = NewPtrSys(size); if (!ptr) return false; Get1DriverState (refnum, dInfos.slots, ptr, size); err = FSMakeFSSpec(vrefNum, dirID, file, &spec); if (err == fnfErr) err = FSpCreate (&spec, creator, type, smSystemScript); if (err != noErr) goto err; err = FSpOpenDF (&spec, fsWrPerm, &ref); if (err != noErr) goto err; err = FSWrite (ref, &size, ptr); FSClose (ref); DisposePtr (ptr); return err == noErr; err: DisposePtr (ptr); return false; }
static PGPError sCreateProc( PFLFileSpecRef ref ) { PGPError err = kPGPError_NoErr; OSStatus macErr = noErr; MyData * myData = GetMyData( ref ); OSType fileCreator; OSType fileType; fileCreator = myData->metaInfo.fInfo.fileCreator; fileType = myData->metaInfo.fInfo.fileType; if( myData->specIsValid ) { macErr = FSpCreate( &myData->spec, fileCreator, fileType, smSystemScript ); if ( macErr != noErr ) { err = kPGPError_FileOpFailed; } } else { err = kPGPError_FileOpFailed; } return( err ); }
static OSStatus strcpyFileSystemRepresentationFromClassicPath(char *nativePath, char * classicPath, long nativePathMaxLength ) { CFURLRef fileAsCFURLRef = 0; Boolean resolveAgainstBase = true; FSRef fileAsFSRef; Boolean gotPath; char pathPStr[256]; FSSpec spec; OSStatus err = 0; strcpy(pathPStr,classicPath); my_c2pstr(pathPStr); err = FSMakeFSSpec(0, 0, (StringPtr)pathPStr,&spec); if(err == fnfErr) { // just means the file does not exist yet err = FSpCreate (&spec,'MPW ','TEXT',smSystemScript); // we should be able to use any creator and type here } if(err) return err; err = FSpMakeFSRef(&spec,&fileAsFSRef); if(err) return err; // Convert the reference to the file to a CFURL fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef); if(fileAsCFURLRef) { gotPath = CFURLGetFileSystemRepresentation(fileAsCFURLRef,resolveAgainstBase,(UInt8 *)nativePath,nativePathMaxLength); CFRelease(fileAsCFURLRef); fileAsCFURLRef = 0; } if(gotPath) return noErr; return -1; // did not get the path }
jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { short tmpRef, vRefNum; long dirID; FInfo finderInfo; FSSpec theSpec; Str255 fName; OSErr osErr; long gestaltResponse = 0; /* Check that FSSpec calls are available. */ osErr = Gestalt( gestaltFSAttr, &gestaltResponse ); if ( ( osErr != noErr ) || !( gestaltResponse & (1<<gestaltHasFSSpecCalls) ) ) ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required"); /* TO DO: add a proper error message to jerror.h. */ /* Check that FindFolder is available. */ osErr = Gestalt( gestaltFindFolderAttr, &gestaltResponse ); if ( ( osErr != noErr ) || !( gestaltResponse & (1<<gestaltFindFolderPresent) ) ) ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required."); /* TO DO: add a proper error message to jerror.h. */ osErr = FindFolder ( kOnSystemDisk, kTemporaryFolderType, kCreateFolder, &vRefNum, &dirID ); if ( osErr != noErr ) ERREXITS(cinfo, JERR_TFILE_CREATE, "- temporary items folder unavailable"); /* TO DO: Try putting the temp files somewhere else. */ /* Keep generating file names till we find one that's not in use */ for (;;) { next_file_num++; /* advance counter */ sprintf(info->temp_name, TEMP_FILE_NAME, next_file_num); strcpy ( (Ptr)fName+1, info->temp_name ); *fName = strlen (info->temp_name); osErr = FSMakeFSSpec ( vRefNum, dirID, fName, &theSpec ); if ( (osErr = FSpGetFInfo ( &theSpec, &finderInfo ) ) != noErr ) break; } osErr = FSpCreate ( &theSpec, '????', '????', smSystemScript ); if ( osErr != noErr ) ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); osErr = FSpOpenDF ( &theSpec, fsRdWrPerm, &(info->temp_file) ); if ( osErr != noErr ) ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); info->tempSpec = theSpec; info->read_backing_store = read_backing_store; info->write_backing_store = write_backing_store; info->close_backing_store = close_backing_store; TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name); }
void QTCmpr_PromptUserForDiskFileAndSaveCompressed (Handle theHandle, ImageDescriptionHandle theDesc) { FSSpec myFile; Boolean myIsSelected = false; Boolean myIsReplacing = false; short myRefNum = -1; StringPtr myImagePrompt = QTUtils_ConvertCToPascalString(kQTCSaveImagePrompt); StringPtr myImageFileName = QTUtils_ConvertCToPascalString(kQTCSaveImageFileName); OSErr myErr = noErr; // do a little parameter checking.... if ((theHandle == NULL) || (theDesc == NULL)) goto bail; if ((**theDesc).dataSize > GetHandleSize(theHandle)) goto bail; // prompt the user for a file to put the compressed image into; in theory, the name // should have a file extension appropriate to the type of compressed data selected by the user; // this is left as an exercise for the reader QTFrame_PutFile(myImagePrompt, myImageFileName, &myFile, &myIsSelected, &myIsReplacing); if (!myIsSelected) goto bail; HLock(theHandle); // create and open the file myErr = FSpCreate(&myFile, kImageFileCreator, (**theDesc).cType, 0); if (myErr == noErr) myErr = FSpOpenDF(&myFile, fsRdWrPerm, &myRefNum); if (myErr == noErr) myErr = SetFPos(myRefNum, fsFromStart, 0); // now write the data in theHandle into the file if (myErr == noErr) myErr = FSWrite(myRefNum, &(**theDesc).dataSize, *theHandle); if (myErr == noErr) myErr = SetFPos(myRefNum, fsFromStart, (**theDesc).dataSize); if (myErr == noErr) myErr = SetEOF(myRefNum, (**theDesc).dataSize); if (myRefNum != -1) myErr = FSClose(myRefNum); bail: free(myImagePrompt); free(myImageFileName); HUnlock(theHandle); }
pascal OSErr FSpCreateCompat(const FSSpec *spec, OSType creator, OSType fileType, ScriptCode scriptTag) { #if !__MACOSSEVENFIVEONEORLATER OSErr result; UniversalFMPB pb; if ( #if !__MACOSSEVENORLATER (!FSHasFSSpecCalls() && !QTHasFSSpecCalls()) || #endif /* !__MACOSSEVENORLATER */ !HasFSpCreateScriptSupportFix() ) { /* If FSpCreate isn't called, this code will be executed */ pb.hPB.fileParam.ioVRefNum = spec->vRefNum; pb.hPB.fileParam.ioDirID = spec->parID; pb.hPB.fileParam.ioNamePtr = (StringPtr) &(spec->name); pb.hPB.fileParam.ioFVersNum = 0; result = PBHCreateSync(&(pb.hPB)); if ( result == noErr ) { /* get info on created item */ pb.ciPB.hFileInfo.ioFDirIndex = 0; result = PBGetCatInfoSync(&(pb.ciPB)); if ( result == noErr ) { /* Set fdScript in FXInfo */ /* The negative script constants (smSystemScript, smCurrentScript, and smAllScripts) */ /* don't make sense on disk, so only use scriptTag if scriptTag >= smRoman */ /* (smRoman is 0). fdScript is valid if high bit is set (see IM-6, page 9-38) */ pb.ciPB.hFileInfo.ioFlXFndrInfo.fdScript = (scriptTag >= smRoman) ? ((char)scriptTag | (char)0x80) : (smRoman); /* Set creator/fileType */ pb.ciPB.hFileInfo.ioFlFndrInfo.fdCreator = creator; pb.ciPB.hFileInfo.ioFlFndrInfo.fdType = fileType; /* Restore ioDirID field in pb which was changed by PBGetCatInfo */ pb.ciPB.hFileInfo.ioDirID = spec->parID; result = PBSetCatInfoSync(&(pb.ciPB)); } } return ( result ); } else #endif /* !__MACOSSEVENFIVEONEORLATER */ { return ( FSpCreate(spec, creator, fileType, scriptTag) ); } }
/* デバッグファイルを作成し、開く */ 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; }
/* * 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); }
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); }
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); }
extern XP_File VR_StubOpen (const char *mode) { XP_File fh = NULL; FSSpec regSpec; OSErr err; short foundVRefNum; long foundDirID; short pathLen; Handle thePath; int bCreate = 0; Ptr finalPath; err = FindFolder(kOnSystemDisk,'pref', false, &foundVRefNum, &foundDirID); if (!err) { err = FSMakeFSSpec(foundVRefNum, foundDirID, "\pNetscape Registry", ®Spec); if (err == -43) { /* if file doesn't exist */ err = FSpCreate(®Spec, ' ', ' ', smSystemScript); bCreate = 1; } if (err == noErr) { err = FSpGetFullPath(®Spec, &pathLen, &thePath); finalPath = NewPtrClear(pathLen+1); BlockMoveData(*thePath, finalPath, pathLen); if (bCreate) fh = fopen( finalPath, XP_FILE_WRITE_BIN ); else fh = fopen( finalPath, "w+b" ); /* this hack to support CW11 MSL C Lib fopen update mode */ DisposePtr(finalPath); } }
NLM_EXTERN void LIBCALL Nlm_FileCreate (Nlm_CharPtr fileName, Nlm_CharPtr type, Nlm_CharPtr creator) { #ifdef OS_MAC Nlm_Int2 fError; Nlm_Char temp [256]; OSType fType; OSType fCreator; FSSpec spec; #else FILE *fp; #endif if (fileName != NULL && fileName [0] != '\0') { #ifdef OS_MAC /* note: the following assumes either full pathname or that the current directory is the proper location to find/create the file */ Nlm_StringNCpy_0(temp, fileName, sizeof(temp)); Nlm_CtoPstr ( temp); fError = FSMakeFSSpec( 0, 0, (StringPtr)temp, &spec); /* file not found, so create it... */ if( fError == fnfErr){ fType = Nlm_GetOSType (type, 'TEXT'); fCreator = Nlm_GetOSType (creator, ' '); FSpCreate( &spec, fCreator, fType, smSystemScript); } #else fp = Nlm_FileOpen (fileName, "w"); if (fp != NULL) { Nlm_FileClose (fp); } #endif } }
/* create icns(icon for MacOS X) with IPIcon */ OSErr MakeXIconWithIPIcon(const FSSpec *theFile,const IPIconRec *ipIcon) { OSErr err; FInfo fndrInfo; short refNum; IconFamilyHandle iconFamily; long count; if (!isIconServicesAvailable) return -1; /* convert IPIcon to icns */ err=IPIconToIconFamily(ipIcon,&iconFamily); if (err!=noErr) return err; /* create a file */ err=FSpGetFInfo(theFile,&fndrInfo); if (err==fnfErr) err=FSpCreate(theFile,kIconPartyCreator,kXIconFileType,smSystemScript); if (err!=noErr) return err; /* open the file */ err=FSpOpenDF(theFile,fsWrPerm,&refNum); if (err!=noErr) return err; /* save icns */ HLock((Handle)iconFamily); count=GetHandleSize((Handle)iconFamily); err=FSWrite(refNum,&count,*iconFamily); err=SetEOF(refNum,count); HUnlock((Handle)iconFamily); DisposeHandle((Handle)iconFamily); /* close the file */ err=FSClose(refNum); return noErr; }
OSErr QTDR_CreateReferenceCopy (Movie theSrcMovie, FSSpecPtr theDstMovieFile, FSSpecPtr theDstMediaFile) { Track mySrcTrack = NULL; Media mySrcMedia = NULL; Movie myDstMovie = NULL; Track myDstTrack = NULL; Media myDstMedia = NULL; Handle myMediaRef = NULL; // data reference for the media file #if !USE_ADDEMPTYTRACKTOMOVIE Fixed myWidth, myHeight; OSType myType; #endif long myFlags = createMovieFileDeleteCurFile | createMovieFileDontCreateResFile; short myResRefNum = 0; short myResID = movieInDataForkResID; OSErr myErr = paramErr; // get the first video track and media in the source movie mySrcTrack = GetMovieIndTrackType(theSrcMovie, 1, VideoMediaType, movieTrackMediaType); if (mySrcTrack == NULL) goto bail; mySrcMedia = GetTrackMedia(mySrcTrack); if (mySrcMedia == NULL) goto bail; // create a file data reference for the new media file myMediaRef = QTDR_MakeFileDataRef(theDstMediaFile); if (myMediaRef == NULL) goto bail; // create a file for the destination movie data myErr = FSpCreate(theDstMediaFile, sigMoviePlayer, MovieFileType, 0); if (myErr != noErr) goto bail; // create a file for the destination movie atom and create an empty movie myErr = CreateMovieFile(theDstMovieFile, sigMoviePlayer, smCurrentScript, myFlags, &myResRefNum, &myDstMovie); if (myErr != noErr) goto bail; // assign the default progress proc to the destination movie SetMovieProgressProc(myDstMovie, (MovieProgressUPP)-1, 0); #if USE_ADDEMPTYTRACKTOMOVIE myErr = AddEmptyTrackToMovie(mySrcTrack, myDstMovie, myMediaRef, rAliasType, &myDstTrack); if (myErr != noErr) goto bail; myDstMedia = GetTrackMedia(myDstTrack); myErr = GetMoviesError(); if (myErr != noErr) goto bail; #else // get some information about the source track and media GetTrackDimensions(mySrcTrack, &myWidth, &myHeight); GetMediaHandlerDescription(mySrcMedia, &myType, 0, 0); // create the destination movie track and media myDstTrack = NewMovieTrack(myDstMovie, myWidth, myHeight, kNoVolume); myErr = GetMoviesError(); if (myErr != noErr) goto bail; myDstMedia = NewTrackMedia(myDstTrack, myType, GetMediaTimeScale(mySrcMedia), myMediaRef, rAliasType); myErr = GetMoviesError(); if (myErr != noErr) goto bail; CopyTrackSettings(mySrcTrack, myDstTrack); #endif // copy the entire source track into the destination track; this copies the track's media // samples into the destination media file myErr = BeginMediaEdits(myDstMedia); if (myErr != noErr) goto bail; myErr = InsertTrackSegment(mySrcTrack, myDstTrack, 0, GetTrackDuration(mySrcTrack), 0); if (myErr != noErr) goto bail; myErr = EndMediaEdits(myDstMedia); if (myErr != noErr) goto bail; // add the movie atom to the data fork of the movie file myErr = AddMovieResource(myDstMovie, myResRefNum, &myResID, NULL); bail: return(myErr); }
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; }
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; }
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); }
OSStatus BeginSave( NavDialogRef inDialog, NavReplyRecord* outReply, FSRef* outFileRef ) { OSStatus status = paramErr; AEDesc dirDesc; AEKeyword keyword; CFIndex len; require( outReply, Return ); require( outFileRef, Return ); status = NavDialogGetReply( inDialog, outReply ); nrequire( status, Return ); status = AEGetNthDesc( &outReply->selection, 1, typeWildCard, &keyword, &dirDesc ); nrequire( status, DisposeReply ); len = CFStringGetLength( outReply->saveFileName ); if ( dirDesc.descriptorType == typeFSRef ) { const UInt32 kMaxNameLen = 255; FSRef dirRef; UniChar name[ kMaxNameLen ]; if ( len > kMaxNameLen ) { len = kMaxNameLen; } status = AEGetDescData( &dirDesc, &dirRef, sizeof( dirRef )); nrequire( status, DisposeDesc ); CFStringGetCharacters( outReply->saveFileName, CFRangeMake( 0, len ), &name[0] ); status = FSMakeFSRefUnicode( &dirRef, len, &name[0], GetApplicationTextEncoding(), outFileRef ); if (status == fnfErr ) { // file is not there yet - create it and return FSRef status = FSCreateFileUnicode( &dirRef, len, &name[0], 0, NULL, outFileRef, NULL ); } else { // looks like file is there. Just make sure there is no error nrequire( status, DisposeDesc ); } } else if ( dirDesc.descriptorType == typeFSS ) { FSSpec theSpec; status = AEGetDescData( &dirDesc, &theSpec, sizeof( FSSpec )); nrequire( status, DisposeDesc ); if ( CFStringGetPascalString( outReply->saveFileName, &(theSpec.name[0]), sizeof( StrFileName ), GetApplicationTextEncoding())) { status = FSpMakeFSRef(&theSpec, outFileRef); nrequire( status, DisposeDesc ); status = FSpCreate( &theSpec, 0, 0, smSystemScript ); nrequire( status, DisposeDesc ); } else { status = bdNamErr; nrequire( status, DisposeDesc ); } } DisposeDesc: AEDisposeDesc( &dirDesc ); DisposeReply: if ( status != noErr ) { NavDisposeReply( outReply ); } Return: return status; }
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); }
int asyncFileOpen(AsyncFile *f, char *fileNamePtr, int fileNameSize, int writeFlag, int semaIndex) { /* Opens the given file using the supplied AsyncFile structure to record its state. Fails with no side effects if f is already open. Files are always opened in binary mode. */ short int fileRefNum; AsyncFileState *state; OSErr err; void * ithisSessionfn; int thisSession; FSSpec theSpec; /* don't open an already open file */ if (asyncFileValid(f)) return success(false); /* build complete routine descriptor, if necessary */ if (asyncFileCompletionProc == nil) { #if TARGET_API_MAC_CARBON asyncFileCompletionProc = NewIOCompletionUPP((pascal void (*) (union ParamBlockRec *) )asyncFileCompletionRoutine); #else asyncFileCompletionProc = NewIOCompletionProc((pascal void (*) (union ParamBlockRec *) )asyncFileCompletionRoutine); #endif } /* copy the file name into a null-terminated C string */ if (fileNameSize > 1000) return success(false); makeFSSpec((char*) fileNamePtr, fileNameSize,&theSpec); f->sessionID = 0; if (writeFlag) { /* first try to open an existing file read/write: */ err = FSpOpenDF(&theSpec,fsRdWrPerm, &fileRefNum); if (err != noErr) { /* file does not exist; must create it. */ err = FSpCreate(&theSpec,'R*ch','TEXT',smSystemScript); if (err != noErr) return success(false); err = FSpOpenDF(&theSpec,fsRdWrPerm, &fileRefNum); if (err != noErr) return success(false); } } else { /* open the file read-only */ err = FSpOpenDF(&theSpec,fsRdPerm, &fileRefNum); if (err != noErr) return success(false); } f->state = (AsyncFileState *) NewPtr(sizeof(AsyncFileState)); /* allocate state record */ if (f->state == nil) { FSClose(fileRefNum); return success(false); } ithisSessionfn = interpreterProxy->ioLoadFunctionFrom("getThisSession", "FilePlugin"); if (ithisSessionfn != 0) thisSession = ((int (*) (void)) ithisSessionfn)(); else thisSession = 0; f->sessionID = thisSession; state = (AsyncFileState *) f->state; state->refNum = fileRefNum; state->writable = writeFlag; state->semaIndex = semaIndex; state->status = IDLE; state->bytesTransferred = 0; state->bufferSize = 0; state->bufferPtr = nil; return 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; }
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); } }