tsh73
Oct 18, 2011
API file truncate
There is an API call for truncating file.
With that, file gets shorter (truncated) instantly, with the
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.
(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""test.dat"
'create file
open fileName$ for output as #1
for i = 1 to 10
print #1,using("########",using("########", i)
next
close #1
'check size, show contents
gosub [checkFile]
if truncateFile( fileName$, 50) then"File"File truncatedOK"OK"
'check size, show contents
gosub [checkFile]
else"Failed"Failed to open file with APIcalls"calls"
end if
end
[checkFile]
open fileName$ for input as #1"File"File length";lof(#1)";lof(#1)
a$=input$(#1, lof(#1))
close #1"Data: ------------""Data: ------------"
print a$"//----------------""//----------------"
return
function truncateFile( fileName$, newSize)
'truncate file (API calls)
'API consts
hFile = 0 'file handle
INVALID.HANDLE.VALUE = -1
calldll #kernel32,"CreateFileA","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",#kernel32,"SetFilePointer", hFile as long, newSize as long, 0 as long, _
_FILE_BEGIN as ulong, r as ulong
'"commit"'"commit" newSize
calldll #kernel32,"SetEndOfFile","SetEndOfFile", hFile as long, r as ulong
'close file
calldll #kernel32,"CloseHandle","CloseHandle", hFile as long, r as boolean
truncateFile = 1
end functioncode