Low-Level File Handling
On occasion, it is necessary to write data to, or read data from, a text file. This is often referred to as low-level file handling . Three types of file access exist: sequential, random, and binary. This text covers only sequential access. You use sequential access to read and write to a text file, such as an error log. You use the Open keyword to open a text file. You use the Input # keyword to read data. You use the Write # keyword to write data. Finally, you use the Close keyword to close the file. Here's an example:Sub LogErrorText()
Dim intFile As Integer
'Store a free file handle into a variable
intFile = FreeFile
'Open a file named ErrorLog.txt in the current directory
'using the file handle obtained above
Open CurDir & "\ErrorLog.Txt" For Append Shared As intFile
'Write the error information to the file
Write #intFile, "LogErrorDemo", Now, Err, Error, CurrentUser()
'Close the file
Close intFile
End Sub
The code uses the FreeFile function to locate a free file handle. The Open keyword opens a file located in the current directory, with the name ErrorLog.txt. The code opens the file in shared mode and for append, using the file handle returned by the FreeFile function. The code then uses the Write # keyword to write error information to the text file. Finally, the Close keyword closes the text file.Chapter 14. The sample code is located in the CHAP14EX.MDB database.