Declare Function WriteFile Lib "kernel32.dll" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, lpOverlapped As Any) As Long
WriteFile writes a series of bytes (originally stored in any variable, array, or structure) to a file. The file must of course have been opened with at least write-level access. If the file is synchronous (not overlapped), the function begins writing to the file at the current position of the file pointer, and the function automatically adjusts the file pointer to point to the byte immediately after the last byte written. If the file is asynchronous (overlapped), the structure passed as lpOverlapped identifies the point to begin writing at, and the program calling the function is responsible for updating the file pointer.
If an error occured, the function returns 0 (use GetLastError to get the error code). If successful, the function returns a non-zero value.
When passing a string as lpBuffer, the ByVal keyword must preceed the string. The keyword is not necessary for any other data types passed for lpBuffer. When passing 0 for lpOverlapped, the expression ByVal CLng(0) must be used.
' This code is licensed according to the terms and conditions listed here.
' Write both a Long (32-bit) number and a String to the file
' C:\Test\myfile.txt. Notice how the ByVal keyword must be used
' when writing a string variable.
Dim longbuffer As Long ' long to write to the file
Dim stringbuffer As String ' string to write to the file
Dim numwritten As Long ' receives number of bytes written to the file
Dim hFile As Long ' handle of the open file
Dim retval As Long ' return value
' Open or create the file being written to.
hFile = CreateFile("C:\Test\myfile.txt", GENERAL_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_ARCHIVE, 0)
If hFile = -1 Then ' the file could not be opened
Debug.Print "Unable to open the file -- it probably does not exist."
End ' abort the program
End If
' Write a Long-type number (27) to the file
longbuffer = 27 ' the Long value to write to the file
retval = WriteFile(hFile, longbuffer, Len(longbuffer), numwritten, CLng(0))
' Write a 10-character string to the file
stringbuffer = "Anonymous!" ' the String to write to the file
retval = WriteFile(hFile, ByVal stringbuffer, 10, numwritten, CLng(0))
' Close the file.
retval = CloseHandle(hFile)
Go back to the alphabetical Function listing.
Go back to the Reference section index.
Last Modified: October 13, 1999
This page is copyright © 1999 Paul Kuliniewicz.
Copyright Information Revised October 29, 2000
Go back to the Windows API Guide home page.
E-mail: vbapi@vbapi.com Send Encrypted E-Mail
This page is at http://www.vbapi.com/ref/w/writefile.html