Home >Backend Development >Golang >How Can I Detect File Changes in Go Using Status Polling?

How Can I Detect File Changes in Go Using Status Polling?

DDD
DDDOriginal
2024-12-02 21:31:16735browse

How Can I Detect File Changes in Go Using Status Polling?

Detect File Changes in Go using Status Polling

In Go, you can detect when a file changes using status polling. While Go does not offer a direct equivalent to the Unix fcntl() function for file change notifications, status polling provides a cross-platform solution:

func watchFile(filePath string) error {
    initialStat, err := os.Stat(filePath)
    if err != nil {
        return err
    }

    for {
        stat, err := os.Stat(filePath)
        if err != nil {
            return err
        }

        if stat.Size() != initialStat.Size() || stat.ModTime() != initialStat.ModTime() {
            break
        }

        time.Sleep(1 * time.Second)
    }

    return nil
}

Usage:

doneChan := make(chan bool)

go func(doneChan chan bool) {
    defer func() {
        doneChan <- true
    }()

    err := watchFile("/path/to/file")
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("File has been changed")
}(doneChan)

<-doneChan

This solution doesn't offer the efficiency of a system call but provides a simple approach that works on all platforms and may suffice for various use cases.

The above is the detailed content of How Can I Detect File Changes in Go Using Status Polling?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn