Truncate a file: Difference between revisions

Content added Content deleted
(Adding PureBasic)
Line 5: Line 5:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
PureBasic has the internal function [http://www.purebasic.com/documentation/file/truncatefile.html TruncateFile] that cuts the file at the current file position and discards all data that follows.
PureBasic has the internal function [http://www.purebasic.com/documentation/file/truncatefile.html TruncateFile] that cuts the file at the current file position and discards all data that follows.
<lang PureBasic>Procedure SetFileSize(File$, length.q)
A more general procedure that allows both cutting at any (e.g. not just the current) location and also handles that possibility that that wanted length is larger than the current file and thereby also allows for extensions is shown below.
<lang PureBasic>Procedure SetFileSize(File$, length.i)
Protected fh, pos, i
Protected fh, pos, i
If FileSize(File$) < length ; Append mode
If FileSize(File$) < length
Debug "File to small, is a directory or does not exist."
ProcedureReturn #False
Else
fh = OpenFile(#PB_Any, File$)
fh = OpenFile(#PB_Any, File$)
If Not fh: ProcedureReturn #False: EndIf
FileSeek(fh, Lof(fh))
For i=Lof(fh) To length
WriteByte(fh, $00)
Next
CloseFile(fh)
Else ; Truncate mode
fh = OpenFile(#PB_Any, File$)
If Not fh: ProcedureReturn #False: EndIf
FileSeek(fh, length)
FileSeek(fh, length)
TruncateFile(fh)
TruncateFile(fh)