swift function to watch a specific file on disk, if changed, do something
In Swift, you can use the FileManager
class to observe file changes and the DispatchSource
to respond to those changes. Here's an example function that watches a specific file on disk and performs an action when the file is modified:
swiftCopy codeimport Foundation
func watchFile(for path: String, onChange: @escaping () -> Void) {
let fileDescriptor = open(path, O_EVTONLY)
if fileDescriptor == -1 {
print("Error: Unable to open the file at path '\(path)'.")
return
}
let queue = DispatchQueue(label: "fileWatcherQueue")
let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fileDescriptor, eventMask: .write, queue: queue)
source.setEventHandler {
onChange()
}
source.setCancelHandler {
close(fileDescriptor)
}
source.resume()
}
// Usage example
let filePath = "/path/to/your/file.txt"
watchFile(for: filePath) {
print("File has been modified.")
}
RunLoop.main.run()
This function takes a file path and a closure onChange
that will be executed when the file changes. The function uses FileManager
to open the file, creates a DispatchSource
to observe file changes, and sets an event handler to execute the onChange
closure when the file is modified.
To use this function, simply provide the file path and a closure to perform an action when the file changes. Note that the example runs indefinitely using RunLoop.main.run()
. Depending on your use case, you may want to adjust this to fit your application's needs.