Truncate a file

From Rosetta Code
Revision as of 12:39, 19 July 2011 by rosettacode>Jofur (Adding PureBasic)
Truncate a file is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

The task is to demonstrate how to truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). The truncation can be achived using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, if no other method is possible. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition and exit.

PureBasic

PureBasic has the internal function TruncateFile that cuts the file at the current file position and discards all data that follows. 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
 If FileSize(File$) < length    ; Append mode
   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)
   TruncateFile(fh)
   CloseFile(fh)
 EndIf
 ProcedureReturn #True

EndProcedure</lang>