Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

Reading raw data from a file

in Questions Posts: 815

Searching the forum I have found several references to reading in data from a file built directly within Codea and saved out as global data.

I have a file which I think is stored as Hex and I’d like to read it in to see if I can manipulate the data. I tried to read it as a png File by renaming the file to .png but Codea must detect file types from their structure so I can’t even read the data into memory. Any ideas?

Comments

  • dave1707dave1707 Mod
    Posts: 6,828

    @Bri_G I have a project that displays the contents of a hex file, but I don’t have time right now. I’ll find it, cut it down to just displaying the file and post it later.

  • Posts: 815

    @dave1707 - no pressure/rush, currently trying to read file on other systems. Would like to see your code - appreciated.

  • dave1707dave1707 Mod
    Posts: 6,828

    @Bri_G Here’s the program to read a hex file. Change the fileName to the file you want to read. Change the size for the number of bytes you want to read. The program will print any ascii character as that character and will print any non ascii characters as (##) where ## is the hex value of that character. This is set to read a file from the Dropbox folder. Let me know if this works for what you want otherwise I can do something else.

    function setup()  
        fileName="Crash.png"
        size=1000
    
        file = os.getenv("HOME").."/Documents/Dropbox.assets/"..fileName
        readBinary()
    end
    
    function readBinary()
        xx={}
        binaryFile=io.open(file,"rb")
        if binaryFile then
            binaryData=binaryFile:read(size)
            binaryFile:close()
            for i=1,#binaryData do
                ch=binaryData:byte(i)
                if ch>=32 and ch<=126 then
                    table.insert(xx,string.char(ch))
                else
                    table.insert(xx,string.format("(%02x)",ch))
                end
            end
            print(table.concat(xx))
        else
            print("Invalid file name or file not found")
        end
    end
    
  • Posts: 815

    @dave1707 - thanks for that, managed to read the file and play around with your code to capture the data in a reasonable format. Now the hard work in deciphering it!! Thanks for the help.

Sign In or Register to comment.