Home > Software engineering >  Share a text file operation module
Share a text file operation module

Time:10-21

Has been used before the open file for input as # num/line input processing text files,

But two problems has been a headache
1) input way is to put all the file is read in operation, so if you only need to read file header is very slow, and binary cannot line input (remember & gt; & lt;)
2) Unix/unix-like newline is CRH (10), the line input is not working...

Based on these two ideas, made up a simple module, hope more directions:)

 
Option Explicit

Public Const FILEMODEL_FlagFileEnd As String="# # # # # # @ # @ END"
Dim FILEMODEL_FileHandleMAX As Long
Dim FILEMODEL_FileHandle () As Long 'Handle of the File, LBound=1
The 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

The Open strFilePath For Binary As # FILEMODEL_FileHandle (FILEMODEL_FileHandleMAX)

FileInputOpen=FILEMODEL_FileHandleMAX 'return index

The Exit Function

FILEMODEL_ERROR_INPUTOPEN:
FileInputOpen=1
End the Function

The Function FileLineInput (handle As Long, Optional UNIXMode As Boolean=False) As String 'UNIX MODE: CRH (10)
On Error GoTo FILEMODEL_ERROR_LINEINPUT
Dim As Long I
Dim intFileNumber As Long
Dim strPreRead As String * 1
Dim strTemp As String
IntFileNumber=FILEMODEL_FileHandle (handle)
If LOF (intFileNumber) - Seek (intFileNumber) & lt; 0 Then FileLineInput=FILEMODEL_FlagFileEnd: Exit Function 'The Last


If UNIXMode=False Then 'Windows

Do Until the Seek (intFileNumber) & gt; LOF (intFileNumber)
The Get # intFileNumber, strPreRead

If strPreRead=CRH (13) Then Exit the Do Else strTemp=strTemp + strPreRead 'Encounter the CR/LF
Loop

Get # intFileNumber, strPreRead 'CRH (10)
FileLineInput strTemp=

The Else
'the UNIX

Do Until the Seek (intFileNumber) & gt; LOF (intFileNumber)
The Get # intFileNumber, strPreRead

If strPreRead=CRH (10) Then Exit the Do Else strTemp=strTemp + strPreRead 'Encounter the LF
Loop

FileLineInput strTemp=
End the If
The Exit Function
FILEMODEL_ERROR_LINEINPUT:
FileLineInput=""
End the Function

The Function FileClose (handle As Long)
On Error GoTo FILEMODEL_ERROR_FILECLOSE
FILEMODEL_FileHandle (handle)=0
Close # handle
FileClose=1
The Exit Function
FILEMODEL_ERROR_FILECLOSE:
FileClose=1
End the Function




Usage is as follows:
 
Sub MMMMM (strInputFile As String, Optional InputUnixMode As Boolean=True)
'UnixMode=True, the newline character for CRH (10); When Mode=False, newline for VBCRLF
Dim intFile1 As Long
Dim strReadline As String

IntFile1=FileInputOpen (strInputFile)

Do
StrReadline=FileLineInput (intFile1 InputUnixMode)
If strReadline=FILEMODEL_FlagFileEnd Then Exit the Do

'work

Loop

Call FileClose (intFile1)

End Sub
  • Related