Qbasicnews.com

Full Version: opening files as binary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can somebody point me to a good tutorial for manipulating files opened in BINARY mode. I haven't ever really used this mode, and I think I'm missing out on a lot because of it. I tried playin' around with it, but couldn't figure out how to do even the simplest stuff, like save data to it, and then load data from it.

Any info is helpful to me Smile

*peace*

Meg.

(thinks this might instead be posted on the newbie forum :p)
Several important things you need to know:

GET #1, , n$ / n% / n&
or
PUT #1, , n$ / n% / n&

no 2nd parameter means you just continue where you left off. Otherwise start GETTing at that byte position.

MOST IMPORTANT FACT:

You MUST defINE any string lengths for it to be any use!!
for instance, this PUTs a bunch of chr$(32)s:

n$ = space$(100)
PUT #1, , n$

Also good for getting, as getting a lot of stuff at once is usually faster than getting a little bit of stuff many times.

You can fill the n$ without changing the length by using MID$(n$,5,1) = "7" for instance... this SHOULD be faster than constantly changing the string length by doing n$ = n$+...
thanks for the response. I see what I was doing wrong, now. The third argument in the PUT/GET line refers to the BYTE position. So when I put an integer into the file, it uses two bytes.

My previous, incorrect code:

Code:
FOR i% = 1 TO 10
  PUT #1, i%, i%
NEXT i%

FOR i% = 1 TO 10
  GET #1, i%, a%
  PRINT a%
NEXT i%

My new, correct code:

Code:
FOR i% = 1 TO 10
  PUT #1, (i% * 2) - 1, i%
NEXT i%

FOR i% = 1 TO 10
  GET #1, (i% * 2) - 1, a%
  PRINT a%
NEXT i%

Fun! Smile

*peace*

Meg.
Quote:thanks for the response. I see what I was doing wrong, now. The third argument in the PUT/GET line refers to the BYTE position. So when I put an integer into the file, it uses two bytes.

Meg...note that if you are getting or putting consecutive data to a binary file, you don't need to keep track of the byte position. The next get or put will automatically occur at the next spot in the file. For example, if you are at location 3 and you get an INT, the next get will start at 5. If you then get a LONG, your next get will start at 9. This is if you leave out the *optional* file-position argument.

What this means in short is that the following works. Suppose you have 2 arrays. One of INT (2-bytes) and one of SINGLE (4-bytes). Each array has 10 elements. You could write them to the a file as follows:

OPEN fileout$ FOR BINARY AS #1

FOR i = 1 to 10

PUT #1, , array1(i)
PUT #1, , array2(i)

NEXT i

CLOSE #1

The resulting file will be 60 bytes long and contain alternating elements from array1 and array2.

Cheers.