Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write text file in appending (utf-8 encoded) in VB6

I have to write a textfile in VB6. I need to do it in appending and utf-8 encoded.

I tried two solutions, one with "TextStream" and another one with "ADODB.Stream".

The first one:

    Set fsoFile = fso.OpenTextFile(FileIn(fi), ForAppending, True)
    fsoFile.WriteLine "<tag>kkkjòòkkkkjlòlk</tag>"
    fsoFile.Close

Works good in appending but how can I write it utf-8 encoded?

The second one:

Dim ST As ADODB.Stream

Set ST = New ADODB.Stream
ST.Mode = adModeReadWrite
ST.Type = adTypeText
ST.Charset = "UTF-8"

ST.Open
ST.LoadFromFile FileIn(fi)
ST.Position = ST.Size
ST.WriteText "<tag>kkkjòòkkkkjlòlk</tag>"
ST.SaveToFile FileIn(fi)
ST.Close

Write correctly in utf-8 but I can't write the file in appending but only with "adSaveCreateOverWrite".

How can I do that? Is there another way?

Thank you very much.

like image 809
epi82 Avatar asked May 04 '12 13:05

epi82


1 Answers

Actually no need for API call.

Option Explicit

Sub testAppend()
    
    Dim fileName
    fileName = "C:\Test\test.txt"
    Dim f As Integer
    f = FreeFile(0)
    Open fileName For Binary Access Write As #f
    Seek #f, LOF(f) + 1
    Dim t
    t = "<tag>" & ChrW(107) & ChrW(107) & ChrW(107) & ChrW(106) & ChrW(242) & ChrW(242) & ChrW(107) & ChrW(107) & ChrW(107) & ChrW(107) & ChrW(106) & ChrW(108) & ChrW(242) & ChrW(108) & ChrW(107) & "</tag>"
    Put #f, , textToBinary(t, "utf-8")
    Close #f
    
End Sub

Function textToBinary(text, charset) As Byte()
    
    With CreateObject("ADODB.Stream")
        .Open
        .Type = 2 ' adTypeText
        .charset = charset
        .WriteText text
        .Position = 0
        .Type = 1 ' adTypeBinary
        textToBinary = .Read
        .Close
    End With
    
End Function```

like image 59
omegastripes Avatar answered Sep 29 '22 02:09

omegastripes