Advertisement
4_2005-2006 Files/ File Controls/ Input/ Output #154359

API AppendToLog

Appends a string to a specified file (or creates the file if needed). Unlike the open/print/close method, this subroutine uses Win32 API calls. This ensures that your application will be able to write to its log file correctly, even if another user has that log file open in an editor during your write attempt. This is the most practical approach to production-quality logging.

AI

Yapay Zeka Özeti: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Kaynak Kod
original-source
Private Function AppendToLog(ByVal lpFileName As String, ByVal sMessage As String) As Boolean
'appends a string to a text file. it's up to the coder to add a CR/LF at the end
'of the string if (s)he so desires.
 'assume failure
 AppendToLog = False
 
 'exit if the string cannot be written to disk
 If Len(sMessage) < 1 Then Exit Function
 
 'get the size of the file (if it exists)
 Dim fLen As Long
 fLen = 0
 
 If (Len(Dir(lpFileName))) Then
 fLen = FileLen(lpFileName)
 End If
 
 'open the log file, create as necessary
 Dim hLogFile As Long
 hLogFile = CreateFile(lpFileName, GENERIC_WRITE, FILE_SHARE_READ, ByVal 0&, _
   IIf(Len(Dir(lpFileName)), OPEN_EXISTING, CREATE_NEW), _
   FILE_ATTRIBUTE_NORMAL, 0&)
 
 'ensure the log file was opened properly
 If (hLogFile = INVALID_HANDLE_VALUE) Then Exit Function
 
 'move file pointer to end of file if file was not created
 If (fLen <> 0) Then
 If (SetFilePointer(hLogFile, fLen, ByVal 0&, FILE_BEGIN) = &HFFFFFFFF) Then
 'exit sub if the pointer did not set correctly
 CloseHandle (hLogFile)
 Exit Function
 End If
 End If
 
 'convert the source string to a byte array for use with WriteFile
 Dim lTemp As Long
 ReDim TempArray(0 To Len(sMessage) - 1) As Byte
 
 For lTemp = 1 To Len(sMessage)
 TempArray(lTemp - 1) = Asc(Mid$(sMessage, lTemp, 1))
 Next
 
 'write the string to the log file
 If (WriteFile(hLogFile, TempArray(0), Len(sMessage), lTemp, ByVal 0&) <> 0) Then
 'the data was written correctly
 AppendToLog = True
 End If
 
 'flush buffers and close the file
 FlushFileBuffers (hLogFile)
 CloseHandle (hLogFile)
 
End Function
Orijinal Yorumlar (3)
Wayback Machine'den kurtarıldı