API file truncate

There is an API call for truncating file.
With that, file gets shorter (truncated) instantly, with the "tail" portion lost.

Of cource you might use old way and:
  • copy part of the file you need to a new file,
  • then delete old file,
  • then rename new file to old name.
But that would take time. And you will need extra disk space.

(Info taken from API-Based File Operations by DennisMcK, and MSDN on SetEndOfFile, SetFilePointer)

So. Here is a function truncateFile( fileName$, newSize) and usage demo.

'api file truncate
fileName$ = "test.dat"
'create file
open fileName$ for output as #1
    for i = 1 to 10
        print #1, using("########", i)
close #1
'check size, show contents
gosub [checkFile]
if truncateFile( fileName$, 50) then
    print "File truncated OK"
    'check size, show contents
    gosub [checkFile]
    print "Failed to open file with API calls"
end if
    open fileName$ for input as #1
        print "File length ";lof(#1)
        a$=input$(#1, lof(#1))
    close #1
    print "Data: ------------"
    print a$
    print "//----------------"
function truncateFile( fileName$, newSize)
'truncate file (API calls)
'API consts
    hFile = 0       'file handle
    calldll #kernel32, "CreateFileA", fileName$ as ptr, _GENERIC_WRITE as ulong, _
        0 as ulong, 0 as long, _OPEN_ALWAYS as ulong, _
        _FILE_ATTRIBUTE_NORMAL as ulong, 0 as long, hFile as long
    if hFile = INVALID.HANDLE.VALUE then
        truncateFile = 0
        exit function
    end if
    'hFile <> INVALID.HANDLE.VALUE then 'file opened successfully
    'set the file pointer to the newSize
    calldll #kernel32,"SetFilePointer", hFile as long, newSize as long, 0 as long, _
        _FILE_BEGIN as ulong, r as ulong
    '"commit" newSize
    calldll #kernel32, "SetEndOfFile", hFile as long, r as ulong
    'close file
    calldll #kernel32, "CloseHandle", hFile as long, r as boolean
    truncateFile = 1
end function