以前一直習慣用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/134065.html
標籤:非技術類
下一篇:提高VB的程式實時性
