'==============================================================================
' Test #3: File I/O - CreateFileA / WriteFile / CloseHandle / DeleteFileA
'==============================================================================
#COMPILE EXE
#DIM ALL

DECLARE FUNCTION CreateFileA LIB "kernel32.dll" ALIAS "CreateFileA" (BYVAL lpFileName AS ASCIIZ PTR, BYVAL dwAccess AS LONG, BYVAL dwShare AS LONG, BYVAL lpSecurity AS QUAD, BYVAL dwCreation AS LONG, BYVAL dwFlags AS LONG, BYVAL hTemplate AS QUAD) AS QUAD
DECLARE FUNCTION WriteFile LIB "kernel32.dll" ALIAS "WriteFile" (BYVAL hFile AS QUAD, BYVAL lpBuf AS ASCIIZ PTR, BYVAL nBytes AS LONG, BYREF lpWritten AS LONG, BYVAL lpOverlapped AS QUAD) AS LONG
DECLARE FUNCTION CloseHandle LIB "kernel32.dll" ALIAS "CloseHandle" (BYVAL hObject AS QUAD) AS LONG
DECLARE FUNCTION DeleteFileA LIB "kernel32.dll" ALIAS "DeleteFileA" (BYVAL lpFileName AS ASCIIZ PTR) AS LONG
DECLARE FUNCTION GetTickCount LIB "kernel32.dll" ALIAS "GetTickCount" () AS LONG

%GENERIC_WRITE = &H40000000
%CREATE_ALWAYS = 2
%FILE_ATTRIBUTE_NORMAL = 128
%INVALID_HANDLE_VALUE = -1
%NULL = 0

FUNCTION PBMAIN() AS LONG
    LOCAL hFile AS QUAD
    LOCAL written AS LONG
    LOCAL content AS STRING
    LOCAL res AS LONG

    content = "Written by PBXA64 via WinAPI"
    hFile = CreateFileA("test_api_output.txt", %GENERIC_WRITE, 0, %NULL, %CREATE_ALWAYS, %FILE_ATTRIBUTE_NORMAL, %NULL)

    IF hFile <> %INVALID_HANDLE_VALUE THEN
        res = WriteFile(hFile, STRPTR(content), LEN(content), written, %NULL)
        res = CloseHandle(hFile)
        PRINT "File written:", written, "bytes"
        res = DeleteFileA("test_api_output.txt")
        PRINT "File deleted"
    ELSE
        PRINT "File creation failed"
    END IF

    PRINT "Uptime:", GetTickCount(), "ms"
    FUNCTION = 0
END FUNCTION
