lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I agree that you need to open the file in binary mode. 

The two problems you've found so far are easily explained.

0x1A is the EOF character.   When reading a file in ascii mode, this character is interpreted to mean end of file,  and the code behaves accordingly.

0x0d and 0x0a are both end of line characters.   Some platforms need both together to indicate end of line.  If you are on one of these platforms, you will see the behavior you described.

There may be other similar translations which occur with other characters.  I vaguely remember that the NUL character (0x00) is a problem on some platforms.  

The purpose of these translations are to simplify writing a text file.  Opening the file in binary mode disables all of these behaviors.


On Dec 24, 2016 12:57 AM, "Creation Elemental" <arceusthe@gmail.com> wrote:
Using the following code I have noticed that it stops reading a file if it reaches the character 1A (decimal: 26). Then, if it is trying to write the character 0A to a file it will write it as 0D0A. I looked at the file with a hexadecimal viewer. I also noticed that after it had been written as 0D0A, if I ran the file again, it would no longer add the 0D as the 0D was already present. If anyone can tell me why this happens (whether it is a problem with my code of with Lua or whatever that would be much appreciated

lua code is as follows

print("Enter File Path:")
a=io.read()
print("Enter Key:")
k,g,c=io.read(),1,io.open(a,"r")
x,n,d=string.len(k),1,c:read("*all")
c:close()
print("Encrypting (0) or Decrypting (1)?")
c,s,f=io.read(),string.len(d),io.open(a,"w")
while g<=s do
b,e,n,g=string.byte(d,g,g),string.byte(k,n,n),n+1,g+1
if n>x then n=n-x end
if c=="0" then y=256-e else y=e end
z=y+b
if z>255 then z=z-256 end
z=string.char(z)
f:write(z)
end
f:close()