[API]
GetFileSize
ReadFile
SetFilePointer
CloseHandle

[INCLUDE]
CreateFile
CharSets_Enum

[CODE]
Private Function TxtFile_ReadOpenEx(ByVal Filename As String, ByRef InOutEncoding As Long, ByRef PureTextSize As Long, ByVal AppendAndSeekEnd As Boolean) As Long
  Dim xLong1 As Long
  Dim xLong2 As Long

  If AppendAndSeekEnd Then
    TxtFile_ReadOpenEx = CreateFile(Filename, OpenExisting, FILE_READWRITE)
    Else
    TxtFile_ReadOpenEx = CreateFile(Filename, OpenExisting, FILE_READ)
    End If
  If Not TxtFile_ReadOpenEx = -1& Then
    PureTextSize = GetFileSize(TxtFile_ReadOpenEx, xLong1)
    If xLong1 = 0& And PureTextSize < &H4000000 Then
      If Not ReadFile(TxtFile_ReadOpenEx, ByVal VarPtr(xLong1), 3&, xLong2, 0&) = 0& Then
        'If xLong2 = 3& Or xLong2 = PureTextSize Then
'Debug.Print Hex(xLong1)
          If (xLong1 And &HFFFF&) = &HFEFF& Then
            If PureTextSize Mod 2& = 0& Then
              PureTextSize = PureTextSize - 2&
              If Not IsUnicode Then Goto Fail
              InOutEncoding = TxtFile_EncodingEnum.CP_WINUNICODE
              If Not AppendAndSeekEnd Then
                If SetFilePointer(TxtFile_ReadOpenEx, 2&, 0&, 0&) = -1& Then GoTo Fail
                GoTo Success
                End If
              End If
            ElseIf (xLong1 And &HFFFFFF) = &HBFBBEF Then
            PureTextSize = PureTextSize - 3&
            InOutEncoding = TxtFile_EncodingEnum.CP_UTF8
            If Not IsUnicode Then Goto Fail
            If Not AppendAndSeekEnd Then
              'If SetFilePointer(TxtFile_ReadOpenEx, 3&, 0&, 0&) = -1& Then GoTo Fail
              GoTo Success
              End If
            End If
          'End If
        End If
      If PureTextSize Mod 2& = 0& Or Not InOutEncoding = TxtFile_EncodingEnum.CP_WINUNICODE Then
        If Not SetFilePointer(TxtFile_ReadOpenEx, 0&, 0&, -2& * CLng(AppendAndSeekEnd)) = -1& Then GoTo Success
        End If
      End If
Fail:
    Call CloseHandle(TxtFile_ReadOpenEx)
    TxtFile_ReadOpenEx = 0&
    End If
Success:
  End Function
