VB6 转换 Unix 和 DOS 文本格式源代码

时间:2022-03-06 09:47:35

因为昨天用到这个功能,所以改写了下以前的一个函数,测试效果不错,有用的着的拷贝去用吧

mUnix2Dos.bas:

---------------------------------------------------------------------------------------------------------------

'模块功能: 转换 Unix 和 DOS 文本格式
'程序改进: 唐细刚 2006-8-1
Public Enum UnixDosConvertType
    Dos2Unix = 0
    Unix2Dos = 1
End Enum

Public Function ConvertUnixOrDosFile(ByVal SourceFile As String, ByVal TargetFile As String, ByVal ConvertType As UnixDosConvertType, Optional DeleteSourceFile As Boolean = False) As Boolean
    On Error GoTo Z
    Dim OpenFileNum As Integer
    Dim SaveFileNum As Integer
    Dim FileBuffer As String
    OpenFileNum = FreeFile
    If OpenFileNum > 0 Then
       Open SourceFile For Input As #OpenFileNum                    'For Input
            SaveFileNum = FreeFile
            If SaveFileNum > 0 Then
               Open TargetFile For Binary As #SaveFileNum           'For Binary
                    Do While Not EOF(OpenFileNum)
                       Line Input #OpenFileNum, FileBuffer          '若为 Unix 格式,则整个文件会被一次性读取
                       If ConvertType = Dos2Unix Then
                          If InStr(FileBuffer, Chr(10)) = 0 Then    '考虑到源文件可能是 Unix 格式
                             FileBuffer = FileBuffer & Chr(10)
                          End If
                       ElseIf ConvertType = Unix2Dos Then
                          If InStr(FileBuffer, Chr(10)) > 0 Then
                             FileBuffer = Replace(FileBuffer, Chr(10), vbCrLf)
                          ElseIf InStr(FileBuffer, vbCrLf) = 0 Then '考虑到源文件可能是 DOS 格式
                             FileBuffer = FileBuffer & vbCrLf
                          End If
                       End If
                       Put #SaveFileNum, , FileBuffer
                    Loop
               Close #SaveFileNum
            End If
        Close #OpenFileNum
        If DeleteSourceFile = True Then Kill SourceFile
        ConvertUnixOrDosFile = True
    End If
    Exit Function
Z:
    If SaveFileNum > 0 Then Close #SaveFileNum
    If OpenFileNum > 0 Then Close #OpenFileNum
 End Function
---------------------------------------------------------------------------------------------------------------