Re: Commands Writing To Binary File

new topic     » goto parent     » topic index » view thread      » older message » newer message
DerekParnell said...
Andy said...

This is just a crude example of what I want do. Is there something wrong that I am doing, cause I get an error when I do this, or rather when I go to try it, it crashes on me.

Apart from the issues that Jeremy has highlighted, the write_file() function still might not be suitable for you. That function is limited to writing out byte values from the input data. This means that the 'data' parameter must be a sequence that only consists of integers between that values 0 and 255. If it contains floating point numbers, of integers outside that range or sub-sequences, it will not write it to disk and in some cases it will even crash your program.

That is why we have the serialize() function. That function converts any Euphoria object into a sequence of bytes, that then can be safely used by write_file.

Using your example ...

procedure SaveFile(sequence filename, object data) 
   result = write_file(filename, serialize(data)) 
   if result = -1 then 
       puts(1,"Cannot save to file!\n") 
   end if 
end procedure 
 
SaveFile("mydata.dat", 1) 

And to read it back in again ...

function LoadFile(sequenced filename) 
    object data 
    data = read_file(filename) 
    if atom(data) then  
        crash("Cannot load from file") 
    else 
        data = deserialize(data) 
        if data[0] = 0 then 
            crash("Saved data was not formatted correctly") 
        else 
            data = data[2] 
        end if 
    end if 
    return data 
end function 

OK, thanks

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu