[API]
SetEndOfFile
WriteFile
LocalAlloc
LocalFree
RtlMoveMemory

[INCLUDE]
CreateFile
CharSets_Enum

[DEFINE]
Private Type TxtFileWriteStruct
  hFile As Long
  ' same offset as in read counterpart!!!
  Encoding As Long
  End Type
Private Const TxtFileWriteStructLen As Long = 8&

[CODE]
Public Function TxtFile_WriteCreateEx(ByVal Filename As String, ByVal Encoding As TxtFile_EncodingEnum, ByVal ByteOrderMark As Boolean) As Long
  Dim xLong1 As Long
  Dim xLong2 As Long
  Dim xType1 As TxtFileWriteStruct

  xType1.hFile = CreateFile(Filename, CreateAlwaysNew, FILE_WRITE)
  If Not xType1.hFile = -1& Then
    If Not SetEndOfFile(xType1.hFile) = 0& Then
      If ByteOrderMark Then
        If Encoding = TxtFile_EncodingEnum.CP_WINUNICODE Then
          xLong1 = &HFEFF&
          If Not WriteFile(xType1.hFile, ByVal VarPtr(xLong1), 2&, xLong2, 0&) = 0& Then
            If (xLong2 = 2&) Then
              GoTo Success
              End If
            End If
          ElseIf Encoding = TxtFile_EncodingEnum.CP_UTF8 Then
          xLong1 = &HBFBBEF
          If Not WriteFile(xType1.hFile, ByVal VarPtr(xLong1), 3&, xLong2, 0&) = 0& Then
            If (xLong2 = 3&) Then
              GoTo Success
              End If
            End If
          ElseIf Encoding = TxtFile_EncodingEnum.CP_ACP Then
          GoTo Success
          End If
        Else
Success:
        TxtFile_WriteCreateEx = LocalAlloc(0&, TxtFileWriteStructLen)
        If Not TxtFile_WriteCreateEx = 0& Then
          xType1.Encoding = Encoding
          Call RtlMoveMemory(ByVal TxtFile_WriteCreateEx, xType1, TxtFileWriteStructLen)
          Exit Function
          End If
        End If
      End If
    Call CloseHandle(xType1.hFile)
    End If
  End Function

Public Sub TxtFile_WriteClose(ByRef hTxtFileOut As Long)
  Dim xType1 As TxtFileWriteStruct

  If Not hTxtFileOut = 0& Then
    Call RtlMoveMemory(xType1, ByVal hTxtFileOut, TxtFileWriteStructLen)
    If Not xType1.hFile = -1& Then
      Call SetEndOfFile(xType1.hFile)
      Call CloseHandle(xType1.hFile)
      End If
    Call LocalFree(hTxtFileOut)
    hTxtFileOut = 0&
    End If
  End Sub
