Read a file to a buffer

Previous topic - Next topic

Kitty Hello

This code reads the notepad.exe to a string buffer and write it in the .app directory to show it worked.

Code (glbasic) Select

LOCAL buffer$
ReadFile("C:/Windows/notepad.exe", buffer$)

// test if it works
OPENFILE(1, "copypad.exe", 0)
WRITESTR 1, buffer$
CLOSEFILE 1





FUNCTION ReadFile: filename$, BYREF buffer$
LOCAL file%=GENFILE()
LOCAL fs% = GETFILESIZE(filename$)
buffer$=""
IF OPENFILE(file%, filename$, 1)
LOCAL i%
LOCAL ndword% = fs%/4 - 1
// read 4 bytes at once (a tad faster)
FOR i% = 0 TO ndword%
LOCAL b%
READLONG file%, b%
INC buffer$, CHR$(bAND(    b%     , 0xff))
INC buffer$, CHR$(bAND(ASR(b%,  8), 0xff))
INC buffer$, CHR$(bAND(ASR(b%, 16), 0xff))
INC buffer$, CHR$(bAND(ASR(b%, 24), 0xff))
NEXT
DEC fs, 4*ndword

FOR i% = 0 TO fs%-1
LOCAL b%
READBYTE file%, b%
INC buffer$, CHR$(b%)
NEXT
CLOSEFILE file%
ENDIF
RETURN LEN(buffer$)
ENDFUNCTION


MrTAToad

The only real problem is that it cant cope with sizes less than 4 bytes :)

FutureCow

#2
I found a couple of minor mistakes in the function so I've fixed them and made it so it can cope with sizes < 4 bytes

Corrections were made to these lines
Code (glbasic) Select

LOCAL ndword% = fs%/4 - 1
to
LOCAL ndword% = fs%/4

FOR i% = 0 TO ndword%
to
FOR i% = 0 TO ndword%-1


Code (glbasic) Select
LOCAL buffer$
ReadFile("C:/Windows/notepad.exe", buffer$)

// test if it works
OPENFILE(1, "copypad.exe", 0)
WRITESTR 1, buffer$
CLOSEFILE 1

FUNCTION ReadFile: filename$, BYREF buffer$
LOCAL file%=GENFILE()
LOCAL fs% = GETFILESIZE(filename$)

buffer$=""
IF OPENFILE(file%, filename$, 1)
LOCAL i%
IF fs > 3
LOCAL ndword% = fs%/4
// read 4 bytes at once (a tad faster)
FOR i% = 0 TO ndword%-1
LOCAL b%
READLONG file%, b%
INC buffer$, CHR$(bAND(    b%     , 0xff))
INC buffer$, CHR$(bAND(ASR(b%,  8), 0xff))
INC buffer$, CHR$(bAND(ASR(b%, 16), 0xff))
INC buffer$, CHR$(bAND(ASR(b%, 24), 0xff))
NEXT
DEC fs%, 4*ndword
ENDIF
FOR i% = 0 TO fs%-1
LOCAL b%
READBYTE file%, b%
INC buffer$, CHR$(b%)
NEXT
CLOSEFILE file%
ENDIF
RETURN LEN(buffer$)
ENDFUNCTION

Kitty Hello


FutureCow

 :enc: It's not often I find a fault in something you've written Gernot! *laugh*

Kitty Hello

You do find a lot of my bugs. Unfortunately :P

Moru

Better find bugs early than late :-)