This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
YoshiE's profile picture

Issues saving data to files

Started by YoshiE, 23 July 2014 - 01:00 PM
YoshiE #1
Posted 23 July 2014 - 03:00 PM
Hello guys,
I was experimenting with the IO API and the FS API.
To save files i stared using a basic command:

function save(text,name)
local file = fs.open(name,"w")
file.write(text)
file.close()
end
So heres my problem:
Im using the HTTP API to receive a file form a cloud in the .nbs format (im not sure if im allowed to put the link here) and if I am saving the file (file handle) using the function up there ill lose some data and some letters are getting corrupted (before: ˇ after: � before: ¥e∑ô after: �e��).
Do I need to convert it to binary not to lose any data?
And is it possible to read line by line out of a file handle (file:seek function is missing)?

Thank your for taking the time to help me!
Lyqyd #2
Posted 23 July 2014 - 03:25 PM
You would need to use a binary file handle to write those characters to disk, but be aware that the file handles from http fetches are in text mode, so you may not be able to get those characters out of it in the first place.
YoshiE #3
Posted 23 July 2014 - 03:56 PM
I am able to write those character (at least some e.g. ¥e∑ô) to the file. I still got some problems with the "invisible" characters in the file: "
". How is it possible to write the binary file data directly to a file? Could you put a basic code here?

I could convert the file before uplaod to binary basic code to be able to get it 1:1 using http download, the question is how can i save a binary code as a file without converting it to a string? (e.g "0100100001100101011011000110110001101111" as http download so it appears as "Hello" in the file?)
Edited on 23 July 2014 - 05:53 PM
Bomb Bloke #4
Posted 24 July 2014 - 02:07 AM
Everything you get from the http API comes in as a string, so you wouldn't convert it to a string… You'd convert from a string to a numeric form, then write that.

Let's say you took the string "0100100001100101011011000110110001101111" and stuck it on your web page, then ported it into a variable called "myString".

You could then use code along these lines:

local myFile = fs.open("output.txt","wb")

for i=0,#myString/8-1 do
	local thisByte = 0
	
	for j=0,7 do thisByte = thisByte + bit.blshift(myString:byte(i*8+8-j)-48, j) end
	
	myFile.write(thisByte)
end

myFile.close()

This converts each character to a numeric value (either a 0 or a 1) using s:byte(), then sticks that value into a specific bit of the next byte to be written using bit.blshift(). Every eight bits, it writes the byte then starts generating the next one.

Though really base64 would probably be a better bet than a straight "ASCII representing binary" deal. The code is nearly the same either way.