Saturday, December 26, 2009

opening and closing files

Example 2:
Another common programming task is opening a file to process it and then closing it before exiting the procedure. As we’ve seen in Chapter 5, all the procedures that deal with files have to protect themselves against unanticipated errors because if they were exited in an abrupt way they wouldn’t correctly close the file. Once again, let’s see how a class can help us to deliver more robust code with less effort:
‘ The CFile class--complete source code
Enum OpenModeConstants
omInput
omOutput
omAppend
omRandom
omBinary
End Enum
Dim m_Filename As String, m_Handle As Integer

(continued) Sub OpenFile(Filename As String, _
Optional mode As OpenModeConstants = omRandom)
Dim h As Integer
‘ Get the next available file handle.
h = FreeFile()
‘ Open the file with desired access mode.
Select Case mode
Case omInput: Open Filename For Input As #h
Case omOutput: Open Filename For Output As #h
Case omAppend: Open Filename For Append As #h
Case omBinary: Open Filename For Binary As #h
Case Else ‘ This is the default case.
Open Filename For Random As #h
End Select
‘ (Never reaches this point if an error has occurred.)
m_Handle = h
m_Filename = Filename
End Sub

‘ The filename (read-only property)
Property Get Filename() As String
Filename = m_Filename
End Property

‘ The file handle (read-only property)
Property Get Handle() As Integer
Handle = m_Handle
End Property

‘ Close the file, if still open.
Sub CloseFile()
If m_Handle Then
Close #m_Handle
m_Handle = 0
End If
End Sub

Private Sub Class_Terminate()
‘ Force a CloseFile operation when the object goes out of scope.
CloseFile
End Sub
This class solves most of the problems that are usually related to file processing, including finding the next available file handle and closing the file before exiting the procedure:
‘ This routine assumes that the file always exists and can be opened.
‘ If it’s not the case, it raises an error in the client code.
Sub LoadFileIntoTextBox(txt As TextBox, filename As String)
Dim f As New CFile
f.OpenFile filename, omInput
txt.Text = Input$(LOF(f.Handle), f.Handle)
‘ No need to close it before exiting the procedure!
End Sub


In many applications, it is helpful to have the capability to read and write information to a disk file. This information could be some computed data or perhaps information loaded into a Visual Basic object.

• Visual Basic supports two primary file formats: sequential and random access. We first look at sequential files.

• A sequential file is a line-by-line list of data. You can view a sequential file with any text editor. When using sequential files, you must know the order in which information was written to the file to allow proper reading of the file.

No comments:

Post a Comment