' c_stdio.pb — C stdio functions simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL fileBuffer(500) AS LONG
    LOCAL bufPos AS LONG
    LOCAL bufSize AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL byteRead AS LONG
    LOCAL byteWritten AS LONG
    LOCAL totalRead AS LONG
    LOCAL totalWritten AS LONG
    LOCAL fopenResult AS LONG
    LOCAL fcloseCount AS LONG
    LOCAL fgetcCount AS LONG
    LOCAL fputcCount AS LONG
    LOCAL fprintfCount AS LONG
    LOCAL fscanfCount AS LONG
    LOCAL iter AS LONG
    LOCAL numOps AS LONG
    LOCAL dataByte AS LONG
    LOCAL formatID AS LONG
    LOCAL formatStr AS STRING
    LOCAL intArg AS LONG
    LOCAL strArg AS STRING

    bufSize = 200

    PRINT "=== C Stdio Simulation ==="

    PRINT "fopen:"
    PRINT "  Opening 'data.txt' for reading..."
    fopenResult = 1
    IF fopenResult = 1 THEN
        PRINT "  File opened successfully"
    ELSE
        PRINT "  Failed to open file"
    END IF

    FOR i = 0 TO 49
        fileBuffer(i) = 65 + i MOD 26
    NEXT i
    bufPos = 0

    PRINT "fgetc (read characters):"
    FOR fgetcCount = 1 TO 20
        IF bufPos < 50 THEN
            dataByte = fileBuffer(bufPos)
            PRINT "  Read: " + CHR$(dataByte) + " (byte " + STR$(dataByte) + ")"
            bufPos = bufPos + 1
            totalRead = totalRead + 1
        ELSE
            PRINT "  EOF reached"
        END IF
    NEXT fgetcCount

    PRINT "fputc (write characters):"
    FOR fputcCount = 1 TO 15
        dataByte = 48 + fputcCount
        fileBuffer(bufPos) = dataByte
        bufPos = bufPos + 1
        totalWritten = totalWritten + 1
        PRINT "  Written: " + CHR$(dataByte) + " (byte " + STR$(dataByte) + ")"
    NEXT fputcCount

    PRINT "fprintf (formatted output):"
    FOR fprintfCount = 1 TO 8
        formatID = fprintfCount
        intArg = fprintfCount * 100
        IF formatID = 1 THEN formatStr = "Integer: %d"
        IF formatID = 2 THEN formatStr = "Hex: 0x%x"
        IF formatID = 3 THEN formatStr = "String: %s"
        IF formatID = 4 THEN formatStr = "Char: %c"
        IF formatID = 5 THEN formatStr = "Unsigned: %u"
        IF formatID = 6 THEN formatStr = "Octal: %o"
        IF formatID = 7 THEN formatStr = "Float: %f"
        IF formatID = 8 THEN formatStr = "Pointer: %p"
        PRINT "  " + formatStr + " -> " + STR$(intArg)
    NEXT fprintfCount

    PRINT "fclose:"
    fcloseCount = 1
    PRINT "  File closed. " + STR$(totalRead) + " bytes read, " + STR$(totalWritten) + " bytes written"

    PRINT "=== End cstdio ==="
    FUNCTION = 0
END FUNCTION
