In that thread we simply looked at taking a file and changing its EOF position.
Here, I am partnering the ability to Put to a position and change the EOF position such that the 'head' of a file is preserved and the 'tail' varies from empty to any length. The head may be a unique ID or a name or whatever.
The test code starts with am empty tail, then a tail with some information, then a tail with more information, then a tail with less information and, finally, an empty tail. The output is the file length, got from LOF(), and the file contents ie head plus tail.
The first use of ThisWriteFile assumes that a file does not exist yet because it uses 'For Binary' and not 'For Binary Access Write' or 'For OutPut'. The first use of SetEOFHT assumes that a file does exist because it uses 'OPEN_EXISTING'. We can always include error trapping but I just wanted to describe the method at this stage.
There are, of course, many ways to achieve the same results but this method, seems to me, to be particularly easy.
Needless to say SetEndOfFile may have many other uses.
As is the code outputs:-
Code: Select all
10 ID:123456
26 ID:123456 Some information
40 ID:123456 Changed information and larger
20 ID:123456 Small info
10 ID:123456
Code: Select all
#Include "windows.bi"
Declare Sub SetEOFHT( As Zstring , As Long, As Long )
Declare Sub ThisReadFile( As String )
Declare Sub ThisWriteFile( As String, As Long, As String )
Dim As String head = "ID:123456 ", tail
Dim As Integer f
Dim As String z = "file.ext"
' No tail
f = Freefile
Open "file.ext" For Output As #f
Put #f, , head
Close #f
ThisReadFile( z )
tail = "Some information"
SetEOFHT( z, Len(head), Len(tail) )
ThisWriteFile( z, Len(head), tail )
ThisReadFile( z )
tail = "Changed information And larger"
SetEOFHT( z, Len(head), Len(tail) )
ThisWriteFile( z, Len(head), tail )
ThisReadFile( z )
tail = "Small info"
SetEOFHT( z, Len(head), Len(tail) )
ThisWriteFile( z, Len(head), tail )
ThisReadFile( z )
' No tail
tail = ""
SetEOFHT( z, Len(head), Len(tail) )
ThisWriteFile( z, Len(head), tail )
ThisReadFile( z )
Sleep
Sub SetEOFHT( filename As Zstring, lenhead As Long, lentail As Long )
Dim As handle hFile = CreateFile( @filename, GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 )
SetFilePointer( hFile, lenhead + lentail, 0, File_Begin)
SetEndOfFile( hFile )
CloseHandle( hFile )
End Sub
Sub ThisWriteFile( filename As String, lenhead As Long, tail As String )
Dim As Long f
f = Freefile
Open "file.ext" For Binary As #f
Put #f, lenhead + 1, tail
Close #f
End Sub
Sub ThisReadFile( filename As String )
Dim As Long f
Dim As String temp
f = Freefile
Open filename For Binary As #f
Print Lof(f);
temp = String(Lof(f), 0)
Get #f, , temp
Close #f
Print " ";temp
End Sub