I haven’t had much time to write, so I figured I could at least share some old -yet useful- PB code in the meantime, as promised.
Quite often you’ll need to load a file right into memory or dump memory into a file, these are relatively trivial tasks but I’m sure someone will eventually benefit from the functions, so here we go:
; Be careful trying to read big files into memory, always check the available RAM is enough before doing anything crazy. Procedure.i FileToMemory( File.s ) ; Returns memory handle if the file was properly loaded, otherwise 0. ; Sanitize filename using your own routine. Define.i fileHandle = ReadFile( #PB_Any, File ) If IsFile(fileHandle) Define.i fileSize = Lof(fileHandle) If fileSize Define.i fileBuffer = AllocateMemory( fileSize ) If fileBuffer If ReadData( fileHandle, fileBuffer, fileSize ) = fileSize CloseFile( fileHandle ) ProcedureReturn fileBuffer Else FreeMemory(fileBuffer) EndIf EndIf EndIf CloseFile(fileHandle) EndIf ProcedureReturn #Null EndProcedure
Procedure.i MemoryToFile( Memory.i, File.s ) ; Returns the amount of written data in bytes, otherwise 0. If Memory If File ; Sanitize filename using your own routine. Define.i MemorySize = MemorySize(Memory) If MemorySize > 0 Define.i fileHandle = CreateFile( #PB_Any, File ) If IsFile( fileHandle ) Define.i DataWritten = WriteData( fileHandle, Memory, MemorySize ) CloseFile( fileHandle ) ProcedureReturn DataWritten EndIf EndIf EndIf EndIf ProcedureReturn #Null EndProcedure
Filename sanitation was not included since this is often part of a separate lib.
Quite frankly functions like these should be part of the official libraries, seeing as how often they’re used… I really do think they should focus on adding new functionality to the language — I hear a rant coming!
Well, not today. Let’s keep it simple.
Cheers!