分享个文本文件操作的模块
以前一直习惯用open file for input as #num/line input处理文本文件。但一直头疼两个问题
1)input方式是先把文件全读进来再操作,这样如果只需要读文件头的话非常慢。而binary又不能line input(记得是><)
2)unix/类unix的换行符是chr(10),line input 不好用……
基于这两点想法,简单编了个module。希望多指点:)
Option Explicit
Public Const FILEMODEL_FlagFileEnd As String = "######@END@#"
Dim FILEMODEL_FileHandleMAX As Long
Dim FILEMODEL_FileHandle() As Long 'Handle of File ,LBound=1
Function FileInputOpen(strFilePath As String) As Long
On Error GoTo FILEMODEL_ERROR_INPUTOPEN
FILEMODEL_FileHandleMAX = FILEMODEL_FileHandleMAX + 1
ReDim Preserve FILEMODEL_FileHandle(FILEMODEL_FileHandleMAX)
FILEMODEL_FileHandle(FILEMODEL_FileHandleMAX) = FreeFile
Open strFilePath For Binary As #FILEMODEL_FileHandle(FILEMODEL_FileHandleMAX)
FileInputOpen = FILEMODEL_FileHandleMAX 'return index
Exit Function
FILEMODEL_ERROR_INPUTOPEN:
FileInputOpen = -1
End Function
Function FileLineInput(handle As Long, Optional UNIXMode As Boolean = False) As String 'UNIX MODE:CHR(10)
On Error GoTo FILEMODEL_ERROR_LINEINPUT
Dim i As Long
Dim intFileNumber As Long
Dim strPreRead As String * 1
Dim strTemp As String
intFileNumber = FILEMODEL_FileHandle(handle)
If LOF(intFileNumber) - Seek(intFileNumber) < 0 Then FileLineInput = FILEMODEL_FlagFileEnd: Exit Function 'The Last
If UNIXMode = False Then 'windows
Do Until Seek(intFileNumber) > LOF(intFileNumber)
Get #intFileNumber, , strPreRead
If strPreRead = Chr(13) Then Exit Do Else strTemp = strTemp + strPreRead 'Encounter the CR/LF
Loop
Get #intFileNumber, , strPreRead 'chr(10)
FileLineInput = strTemp
Else
'UNIX
Do Until Seek(intFileNumber) > LOF(intFileNumber)
Get #intFileNumber, , strPreRead
If strPreRead = Chr(10) Then Exit Do Else strTemp = strTemp + strPreRead 'Encounter the LF
Loop
FileLineInput = strTemp
End If
Exit Function
FILEMODEL_ERROR_LINEINPUT:
FileLineInput = ""
End Function
Function FileClose(handle As Long)
On Error GoTo FILEMODEL_ERROR_FILECLOSE
FILEMODEL_FileHandle(handle) = 0
Close #handle
FileClose = 1
Exit Function
FILEMODEL_ERROR_FILECLOSE:
FileClose = -1
End Function
用法如下:
Sub MMMMM(strInputFile As String, Optional InputUnixMode As Boolean = True)
'UnixMode=True时,换行符为chr(10);当Mode=False时,换行符为vbcrlf
Dim intFile1 As Long
Dim strReadline As String
intFile1 = FileInputOpen(strInputFile)
Do
strReadline = FileLineInput(intFile1, InputUnixMode)
If strReadline = FILEMODEL_FlagFileEnd Then Exit Do
'干活吧
Loop
Call FileClose(intFile1)
End Sub
补充:VB , 非技术类