4

I have a text file, lets call it C:\to_run.txt. I'd like my Autohotkey script to 'listen' to this file in such a way that when it detects a change, it performs an action immediately based on the contents of the file, and then make the file blank again.

I can handle the last parts, so really I'm asking for an efficient way to detect file changes? I say efficient because my Autohotkey script is getting rather long and I don't want this listening function to hang up the rest of the script in any way.

brollin
  • 110
  • 1
  • 11

2 Answers2

7

Assuming we are really talking of only one file to check on: Surely not as beautiful as Sidola's answer, but without the need for external libraries:

#persistent

lastFileContent := ""
setTimer, checkFile, 20
return

checkFile:
fileread newFileContent, changingDocument.txt
if(newFileContent != lastFileContent) {
    lastFileContent := newFileContent
    msgbox, content changed to: %newFileContent%
}
return

In this case, for checking on larger files, it might be better to compare MD5-checksums instead of the whole file content.

Note: I have not tested the performance implications on this. This script opens up the file 50 times per second, could be pretty hard drive consuming.

phil294
  • 10,038
  • 8
  • 65
  • 98
  • I like this answer, too. Thanks. I'm checking on a smaller file so this is applicable. – brollin Jun 03 '15 at 18:43
  • 1
    HaHa - or you could change the interval period in the SetTimer to say every minute, and, or really, just check if the time stamp changed on the file (save on wear and tear) . . . – PGilm Jun 26 '19 at 14:42
6

Check out WatchDirectory()

Just make sure you're running the latest version of AHK.

To get it up and running, first download these three scripts and save them to your /lib folder.

After that, simply point to to wherever you want to look, provide a callback function and if you want, a third param to watch for specific changes. Refer to this forum post for full documentation.

If you drop this script in its own folder, save it and run it, then save it again, it should detect changes to that script file.

#Persistent

WatchDirectory(A_ScriptDir "\|.ahk\", "Callback", 0x10)
return

Callback(param1, param2) {
    msgBox % param1 "`n" param2
}

Note however, it will fire twice whenever the file is changed. This seems to be a Windows behaviour from what I can gather.

Sid
  • 1,709
  • 1
  • 10
  • 17
  • 1
    Note that there is a newer re-implementation of `WatchDirectory()` called [`WatchFolder()`](https://www.autohotkey.com/boards/viewtopic.php?t=8384) (or [here](https://github.com/AHK-just-me/WatchFolder) on GitHub) - it might be easier to use because it has fewer dependencies and also provides a very helpful example. – Marcus Mangelsdorf Feb 26 '21 at 18:31