OpenFile() macro for read-only access and truncation
Posted: Thu Dec 08, 2016 9:41 pm
Suggested by Josh: http://www.purebasic.fr/english/viewtop ... =3&t=67123
I actually quite partial to the Read/Open/Create paradigm. It's easy to remember and I don't have to hunt for the right constant every time I want to read a file immutably or truncate an existing file.
If you happen to find it confusing and would prefer something a bit more C-like, here is a macro just for you:
I actually quite partial to the Read/Open/Create paradigm. It's easy to remember and I don't have to hunt for the right constant every time I want to read a file immutably or truncate an existing file.
If you happen to find it confusing and would prefer something a bit more C-like, here is a macro just for you:
Code: Select all
#PB_File_ReadOnly=1<<21
#PB_File_Truncate=1<<22
Procedure _PB_OpenFile(File.i, FileName.s, Flags.i)
If Not Flags&#PB_File_ReadOnly And Not Flags&#PB_File_Truncate
ProcedureReturn OpenFile(File,Filename.s,Flags)
EndIf
If Flags&#PB_File_Append Or
(Flags&#PB_File_ReadOnly And Flags&#PB_File_Truncate)
DebuggerError("OpenFile(): invalid value specified for parameter 'Flags'.")
EndIf
If Flags&#PB_File_ReadOnly
ProcedureReturn ReadFile(File,Filename.s,Flags&(~#PB_File_ReadOnly))
EndIf
ProcedureReturn CreateFile(File,Filename.s,Flags&(~#PB_File_Truncate))
EndProcedure
Macro OpenFile(File, FileName, Flags)
_PB_OpenFile(File,FileName,Flags)
EndMacro
File=OpenFile(#PB_Any,"C:\test",#PB_File_Truncate)
WriteString(File,"It works!")
CloseFile(File)
File=OpenFile(#PB_Any,"C:\test",#PB_File_ReadOnly|#PB_File_NoBuffering)
If Not WriteString(File,"You'll never see this")
Debug "No bytes written!"
EndIf
Debug ReadString(File)
CloseFile(File)