The API functions “_hwrite” and “_hread” can be useful for writing arrays directly to files and, at some later time, reading these files directly into arrays having the same structure. They are fast and easy to use:
'this API function is used to write arrays to binary files:Declare Function hwrite Lib "Kernel" Alias "_hwrite" _ (ByVal hFile As Integer, _ hpbBuffer As Any, ByVal cbBuffer As Long) As Long'this API function is used to read arrays from binary files:Declare Function hread Lib "Kernel" Alias "_hread" _ (ByVal hFile As Integer, _ hpbBuffer As Any, ByVal cbBuffer As Long) As Long
The next routine writes a two-dimensional integer array (“integer_array”) to a binary file (“binary_file”) with the API function “hwrite.” The array can later be read back from the file with a nearly identical routine calling the “hread” API function. It is traightforward to modify this procedure for other sizes and types of arrays (except for arrays of user-defined types and variable-length strings), but it cannot be made generic over any number of array dimensions because of the way these API functions are called:
Sub WriteIntegerArrayToFile_ (ByVal binary_file As String, _ integer_array() As Integer)Const INTEGER_BYTE_SIZE = 2Dim binary_file_handle As Integer, _ dos_file_handle As IntegerDim bytes_written As Long, bytes_to_write As Long 'get the size of the array in bytes: bytes_to_write = _ (UBound(integer_array, 1) - _ LBound(integer_array, 1) + 1) _ (UBound(integer_array, 2) - _ LBound(integer_array, 2) + 1) _ INTEGER_BYTE_SIZE 'open the file in binary mode: binary_file_handle = FreeFile Open binary_file For Output As binary_file_handle dos_file_handle = _ FileAttr(binary_file_handle, 2) 'make the API call: If dos_file_handle <> 0 Then bytes_written = _ hwrite(dos_file_handle, integer_array ( _ LBound(integer_array, 1), _ LBound(integer_array, 2)), _ bytes_to_write) End If Close binary_file_handleEnd Sub