分享个文本文件操作的模块

一朝风月 一朝风月 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
以前一直习惯用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
...全文
评论
收藏 已收藏
分享
返回顶部
一朝风月
非技术类 743 成员 26,904 内容