Saving arrays

Previous topic - Next topic

Richard Rae

How would you save an array to a file and then reload that array later.

Kitty Hello

how many dimensions?

Robert

I have also this question regarding a 4 dimension array.

Robert

To be more specifik. Is there any method to create files with a loop or a method to save data in another form? I have thought about save in a bitmap.

In dark basic there is a command to save an array in a file so it should be possible. 

nabz32

#4
you mean like

Code (glbasic) Select
FOR x = 0 to bounds( 0 , data[] ) - 1

FOR y = 0 to bounds( 1 , data[] ) - 1

readbyte fileChannel ,  data[x][y]

NEXT

NEXT


?

Ian Price


Yep, look up SAVEWORD, SAVEBYTE, READWORD, READBYTE etc.

Here's a quick example with a 2D array. It sets up an array. Saves the data. Clears the data from array memory. Loads the data, then displays it -

Code (glbasic) Select

// --------------------------------- //
// Project: test
// Start: Monday, April 18, 2016
// IDE Version: 12.656


// SETCURRENTDIR("Media") // go to media files

GLOBAL map%[]

DIM map[5][5]

FOR x=0 TO 4
FOR y=0 TO 4
map[x][y]=RND(9)
NEXT
NEXT

save_data()

clear_data()

load_data()

show_data()


// Save data
FUNCTION save_data:

LOCAL x%, y%

LOCAL file$="mydata.dat"

OPENFILE (1,file$,0)

FOR y=0 TO 4
FOR x=0 TO 4
  WRITEWORD 1,map[x][y]
NEXT
NEXT

CLOSEFILE 1

ENDFUNCTION


// Load data
FUNCTION load_data:

LOCAL x%, y%

LOCAL file$="mydata.dat"

LOCAL ok%=DOESFILEEXIST(file$)

IF ok

OPENFILE (1,file$,1)

  FOR y=0 TO 4
  FOR x=0 TO 4
   READWORD 1,map[x][y]
  NEXT
  NEXT

CLOSEFILE 1

ENDIF

ENDFUNCTION


// Clear data
FUNCTION clear_data:

FOR x=0 TO 4
FOR y=0 TO 4
  map[x][y]=0
NEXT
NEXT

ENDFUNCTION


// show loaded data
FUNCTION show_data:

FOR x=0 TO 4
FOR y=0 TO 4
  PRINT map[x][y],x*10,y*10
NEXT
NEXT

SHOWSCREEN

KEYWAIT

ENDFUNCTION

I came. I saw. I played.

kanonet

Actually its aso possible to MEM2SPRITE an array (not sure if only 1dim or also 4dim) and save it as image. At least if we are talking about integer arrays. If you save it as PNG, you get loseless compression.
Lenovo Thinkpad T430u: Intel i5-3317U, 8GB DDR3, NVidia GeForce 620M, Micron RealSSD C400 @Win7 x64

Robert

Ok thanks, its that stright forward. I haven't worked so much with files in GLB and thought it was more complicated.