Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

[AHK_L] possible bug in file.length, file.pos



  • Please log in to reply
2 replies to this topic
wOxxOm
  • Members
  • 371 posts
  • Last active: Feb 20 2015 12:10 PM
  • Joined: 09 Feb 2006
There seems to be a bug in AHK_L's handling of file.length and file.pos/.position/.tell(), see comments in the code. Tried on x86 unicode v1.1.08.00 and .01
file:=fileopen("test.txt","w","utf-8")
file.write("12345678")	;filesize is now BOM+text = 3+8 = [color=#0000FF]11 [/color]bytes
file.close()

file:=fileopen("test.txt","rw","utf-8")
txt:=file.read()
msgbox % file.pos ; [color=#0000FF]11 (correct)[/color]

file.pos:=0
file.write(txt)
msgbox % file.pos ;  [color=#0000FF]8 (unexpected[/color], I strongly think there should be a way to rewrite a file so that BOM is intact or written anew before actual data when file pointer is 0, that is without reopening file handle, and without manual calculation of real BOM size which may vary between 2 and 4 bytes depending on encoding used)

file.length:=file.pos
msgbox % file.pos ;  [color=#0000FF]16 (wrong, file contains garbage )[/color]
file.close()

The issue of garbage can be circumvented by:
p:=file.pos
file.pos:=0
file.length:=p
file.close()


Lexikos
  • Administrators
  • 9844 posts
  • AutoHotkey Foundation
  • Last active:
  • Joined: 17 Oct 2006
You just need to flush the buffer before setting the Length:
file.__Handle
file.Length := file.Pos
This bug has already been reported.

Lexikos
  • Administrators
  • 9844 posts
  • AutoHotkey Foundation
  • Last active:
  • Joined: 17 Oct 2006
✓  Best Answer
This commit fixes the issues with File.Length.

I strongly think there should be a way to rewrite a file so that BOM is intact or written anew before actual data when file pointer is 0, that is without reopening file handle, and without manual calculation of real BOM size which may vary between 2 and 4 bytes depending on encoding used


As you've explicitly set the file pointer to 0, the correct behaviour is to write the data at position 0, which is exactly what is happening. If you want a BOM, write one, or don't set the position to 0. "Manual calculation of real BOM size" is extremely simple since it can only be 3 (UTF-8) or 4 (UTF-16) bytes, and you already know what encoding the file is in. (If you didn't, you could use File.Encoding.)