getFileSize and setFileSize procedures for File and AsyncFile

Platform independent procedure to set a file length. Useful when
replacing file content.
This commit is contained in:
Emery Hemingway 2017-04-04 20:26:59 -05:00
commit bc5c2d8414
No known key found for this signature in database
GPG key ID: E7AB426C639DCB96
4 changed files with 34 additions and 5 deletions

View file

@ -52,6 +52,8 @@ proc c_ferror(f: File): cint {.
importc: "ferror", header: "<stdio.h>", tags: [].}
proc c_setvbuf(f: File, buf: pointer, mode: cint, size: csize): cint {.
importc: "setvbuf", header: "<stdio.h>", tags: [].}
proc c_ftruncate(f: FileHandle, len: clong): cint {.
importc: "ftruncate", header: "<unistd.h>".}
proc raiseEIO(msg: string) {.noinline, noreturn.} =
sysFatal(IOError, msg)
@ -373,6 +375,11 @@ proc getFileSize(f: File): int64 =
result = getFilePos(f)
setFilePos(f, oldPos)
proc setFileSize(f: File, size: int64) =
## Set a file length.
if c_ftruncate(getFileHandle f, size.clong) == -1:
raiseEIO("cannot truncate file")
proc readFile(filename: string): TaintedString =
var f: File
if open(f, filename):