Adding text to top of txt file using File.Write(xxx, "a") and File.Seek(0,0)

Get help with using AutoHotkey and its commands and hotkeys
Heezea
Posts: 53
Joined: 30 Sep 2013, 21:33

Adding text to top of txt file using File.Write(xxx, "a") and File.Seek(0,0)

01 Oct 2015, 11:35

I'm trying to add text to the top of a txt file (see testing script below) using File.Write(xxx, "a") and File.Seek(0,0). However, the top line just gets overwritten. I would like the text I want to add to get inserted in front of the first character of the file. Can anyone help me with this please?

I do realize I can just read the entire text file into a string or array and then add my new text to the top, then overwrite the entire file. I guess I'm concerned this may slow things down if my file gets really large?

Code: Select all

#SingleInstance Force
global DebugFileFull := "test.txt"

NumpadEnter::
	Debug("a")
	Debug("ab")
	Debug("abc`r`n")
	Debug("abcd`r`n")
	Debug("abcde")
return

Debug(DebugText)
{
	File := FileOpen(DebugFileFull, "a")
	File.Seek(0, 0)
	
	If (!RegExMatch(DebugText, "[`r`n]$"))
	{
		DebugText := DebugText "`r`n"
	}
	Else
	{
		DebugText := DebugText
	}
	
	File.Write(DebugText)
	File.Close()
	
	Run, %DebugFileFull%
	Sleep 100
	return
}
I googled/searched a bit and this was the most relevant thread I could find, but it still doesn't really answer my question.
http://www.autohotkey.com/board/topic/7 ... text-file/

Thanks,
lexikos
Posts: 6668
Joined: 30 Sep 2013, 04:07
GitHub: Lexikos

Re: Adding text to top of txt file using File.Write(xxx, "a") and File.Seek(0,0)

01 Oct 2015, 20:47

Heezea wrote:I guess I'm concerned this may slow things down if my file gets really large?
If the file fits into RAM, doing it that way will be faster. If the file does not fit into RAM, it will either fail completely or use up all RAM and them some pagefile, which will slow everything down.

One way or another, you need to read the file and write the data back at the correct position (i.e. 0 + the length of data you are inserting). If you don't want to read the entire file into memory, you can read in some portion at a time. Read from the end first and work toward the start of the file to avoid overwriting data you haven't moved yet.

Note that the length of the string is not necessarily the number of bytes it will take, due to encoding differences. You can use StrPut(string, encoding) to account for this.

If the file is a text file with a UTF-8 or UTF-16 byte order mark, you would need to account for that when setting the starting position (i.e. Seek(2) or Seek(3) instead of Seek(0)).

Return to “Ask For Help”

Who is online

Users browsing this forum: Bing [Bot], Tom Harding and 236 guests