Note - I have re-written this question from scratch to simplify the problem...

The following function writes out a record to a binary file:

Public Type TestRecord
    Available As Boolean
    Inidcator As String
End Type

Private Sub WriteTestRecord(ByVal RecCount As Integer)

    Dim Fn As Integer, CN As Integer
    Dim filename As String
    Dim EmpRec As TestRecord
    Dim clk() As TestRecord
    ReDim clk(1 To RecCount)

    Debug.Print Len(EmpRec)

    filename = "C:\TestRecFile.bin"

    If Len(Dir(filename)) > 0 Then Kill filename

    Fn = FreeFile
    Open filename For Random As #Fn Len = Len(EmpRec)
    For CN = 1 To RecCount
        EmpRec = clk(CN)
        Put #Fn, , EmpRec
    Next CN
    Close #Fn

End Sub

Note that Len(EmpRec) = 6 when stepping through this code

If I call the function and write out one record - it writes out only 4 bytes:

Call WriteTestRecord(1) 'file length is 4 bytes

If I call the function and write out more than one record - it writes out (RecCount*6) - 2 bytes:

Call WriteTestRecord(10) ' file length is 58 bytes

This is caused by the fact that I have a non-fixed length string in my Type but why is the the first record a different length than all the others?

有帮助吗?

解决方案

It is not that thr first record is wrong, it is that the last record is wrong.

You can see this if you set Available to True just before each write and look at the file.

Your UDT is only 4 bytes, so on the first write you have 4 bytes in the file. But then when you write the 2nd record, VB is first padding Rec#1 in the file with nulls to the 6 byte length you supplied in the Open. It then writes the 4 byte record (rec #2). This process is repeated on every write. It is always the last record that is short.

What is interesting is that the Close does not also pad the last record of 4 byte upto 6 bytes.

其他提示

VB6 variable length strings are pointers to BSTR structures. According to the language spec, they can be NULL. That means the pointer value in the type definition would be zero. I can see VB6 doing something like skipping those bytes when writing it out.

As you mention in your edited question, the correct answer is to use fixed length strings if you're going to write the structure out to a random access file.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top