I'm trying to find a way to empty a text file with Autohotkey. Unfortunetely I was unable to find any build in function that allowes you to do just that. The best solution I could come up with would be:
FileRead, TheText, file.txt
StringReplace, NewText, TheText, 'text to search for', 'replacement text', All
FileDelete, file.txt
FileAppend, %NewText%, file.txt
However, this solution won't work for me because I'm writing a tool that will add or delete content from the Windows hosts file. Deleting the hosts file is out of the question ofcourse.
So instead I'm loading the hosts file content into a variable, replace any addition made by my program with an empty string (to restore the original hosts file content) inside this variable and write it back to the hosts file. But in order to do that I need to empty the file first or it would just append the variable to the existing content.
For those who are curious about my program:
The program will enable/disable the automatic Skype login feature on outlook.com or hotmail.com. Ofcourse without cauing any problems for the mail functions or the Skype client.
Here is a way using a fileobject (req ahk 1.1+)
just put this example in a new script file and run it to see how it works
/* String1
* String2
* String3
* String4
* String5
* String6
* String7
* String8
* String10
*/
msgbox % CutString(A_ScriptFullPath, "String7")
CutString(filePath, Needle)
{
fileObj := FileOpen(filePath, "rw"), pointerPos := fileObj.Pos, RegExMatch(fileObj.read(), "O)" needle, match)
fileObj.Seek(0), newText .= fileObj.read(match.pos-1), fileObj.Seek(match.pos + match.Len), newText .= fileObj.read()
fileObj.Seek(pointerPos), fileObj.Write(newText), fileObj.length := StrLen(newText), fileObj.Close()
return match.value
}
This function uses RegEx to find the pos and size of "needle" string in a file and then rewrites and resizes the file content without it.
You can also rewrite the function to simply cut out lines from the file.
I hope this does what your need