these were adapted from the functions in binreadwrite.ahk provided by PhilLo, and were designed for writing or reading just once; they open and close the handles automatically.
readfiletovar(filename, vartowritecontentsoffileto, bytestoread, startlocation, offset)
startlocation can be -1 for dont move, 0 for start at beginning, 1 for current location, 2 for end of file, and offset is the number of bytes to the left of startlocation to begin reading from (which can be negative). 0 stands for at specified start location
Code:
readfiletovar(_filename, byref _data, _byteNB = 0, _MoveMethod = -1, _offset = 0)
{
local handle, granted, read
handle := Dllcall("CreateFile", "Str", _filename, "UInt", 0x80000000, "UInt", 3, "UInt", 0, "UInt", 3, "UInt", 0, "UInt", 0)
if (handle = INVALID_HANDLE_VALUE or handle = 0)
{
errorlevel = -1
return, -1
}
if (_moveMethod != -1)
{
_offset := DllCall("SetFilePointer", "UInt", handle, "Int", _offset, "UInt", 0, "UInt", _moveMethod)
if (_offset = -1)
{
ErrorLevel = -2
dllcall("CloseHandle", "UInt", handle)
return -2
}
}
if (_byteNB = 0)
{
_byteNB := Dllcall("GetFileSize", "UInt", handle, "UInt", 0)
if (_byteNB = 0xFFFFFFFF)
{
errorlevel = -3
dllcall("CloseHandle", "UInt", handle)
return -3
}
}
granted := varsetcapacity(_data, _byteNB, 0)
if (granted < _byteNB)
{
errorlevel := %granted%
dllcall("CloseHandle", "UInt", handle)
return -4
}
if (dllcall("ReadFile", "UInt", handle, "Str", _data, "UInt", _byteNb, "UInt *", read, "UInt", 0) = 0)
{
errorlevel := -5
dllcall("CloseHandle", "UInt", handle)
return -5
}
dllcall("CloseHandle", "UInt", handle)
return read
}
writevartofile(filename, varcontainingdatatowritetofile, bytestowrite, startingposition, offset)
startlocation can be -1 for dont move, 0 for start at beginning, 1 for current location, 2 for end of file, and offset is the number of bytes to the left of startlocation to begin reading from (which can be negative). 0 stands for at specified start location
Code:
writevartofile(_filename, byref _data, _byteNB, _movemethod, _offset)
{
local handle, datasize, written
handle := dllcall("CreateFile", "Str", _filename, "UInt", 0x40000000, "UInt", 3, "UInt", 0, "UInt", 4, "UInt", 0, "UInt", 0)
if (handle = INVALID_HANDLE_VALUE or handle = -1)
{
errorlevel := -1
return, -1
}
if (_moveMethod != -1)
{
_offset := DllCall("SetFilePointer", "UInt", handle, "Int", _offset, "UInt", 0, "UInt", _moveMethod)
if (_offset = -1)
{
errorLevel = -2
dllcall("CloseHandle", "UInt", handle)
return -2
}
}
datasize := varsetcapacity(_data)
if (_byteNB < 1 or byteNB > datasize)
_byteNB := datasize
if (dllcall("WriteFile", "UInt", handle, "Str", _data, "UInt", _byteNb, "UInt *", written, "UInt", 0) = 0 or written < _byteNB)
{
errorlevel := -3
dllcall("CloseHandle", "UInt", handle)
return -3
}
dllcall("CloseHandle", "UInt", handle)
return written
}