find the last accessed date of a directory in go

We can use the os.Stat function to get the file/directory's information, which includes the last accessed time. Here's an example code snippet:

main.go
package main

import (
    "log"
    "os"
)

func main() {
    dir := "/path/to/directory"
    fi, err := os.Stat(dir)
    if err != nil {
        log.Fatal(err)
    }
    lastAccessed := fi.ModTime()
    log.Printf("Last accessed time of %s: %v", dir, lastAccessed)
}
269 chars
17 lines

In this code, we first define the directory path that we want to check the last accessed time for. We then use the os.Stat function to retrieve the file information of the directory, which includes metadata such as file size, permissions, and the last accessed time. We check for any errors that may occur during this operation using the err variable.

Then, we use the ModTime method of the FileInfo structure to retrieve the last accessed time of the directory. Finally, we log the result using the log.Printf function.

Note: ModTime() returns the modified time of the file but for directories, it returns the time of the most recent change. Hence, it represents the last accessed time for directories.

related categories

gistlibby LogSnag