如何获取文件的ctime,atime,mtime并进行更改

如何获取文件的ctime,atime,mtime并进行更改

问题描述:

如何使用Go来获取文件的ctime,mtime,atime并进行更改?

How can I get file's ctime, mtime, atime use Go and change them?

在Go 1.1.2中, * os.Stat只能获取mtime * os.Chtimes可以更改mtime和atime,但不能更改ctime.

In Go 1.1.2, * os.Stat can only get mtime * os.Chtimes can change mtime and atime but not ctime.

Linux

Linux

ctime

ctime是索引节点或文件更改时间. ctime在以下时间更新 文件属性已更改,例如更改所有者,更改 许可或将文件移动到其他文件系统,但也会 修改文件时更新.

ctime is the inode or file change time. The ctime gets updated when the file attributes are changed, like changing the owner, changing the permission or moving the file to an other filesystem but will also be updated when you modify a file.

文件ctime和atime取决于操作系统.对于Linux,更改索引节点或文件时,Linux将ctime设置为当前时间戳.

The file ctime and atime are OS dependent. For Linux, ctime is set by Linux to the current timestamp when the inode or file is changed.

在Linux上,这是一个通过将atime和mtime设置为其原始值来隐式更改ctime的示例.

Here's an example, on Linux, of implicitly changing ctime by setting atime and mtime to their original values.

package main

import (
    "fmt"
    "os"
    "syscall"
    "time"
)

func statTimes(name string) (atime, mtime, ctime time.Time, err error) {
    fi, err := os.Stat(name)
    if err != nil {
        return
    }
    mtime = fi.ModTime()
    stat := fi.Sys().(*syscall.Stat_t)
    atime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec))
    ctime = time.Unix(int64(stat.Ctim.Sec), int64(stat.Ctim.Nsec))
    return
}

func main() {
    name := "stat.file"
    atime, mtime, ctime, err := statTimes(name)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(atime, mtime)
    fmt.Println(ctime)
    err = os.Chtimes(name, atime, mtime)
    if err != nil {
        fmt.Println(err)
        return
    }
    atime, mtime, ctime, err = statTimes(name)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(atime, mtime)
    fmt.Println(ctime)
}

输出:

2014-01-02 02:21:26.262111165 -0500 EST 2014-01-02 02:18:13.253154086 -0500 EST
2014-01-02 02:21:25.666108207 -0500 EST
2014-01-02 02:21:26.262111165 -0500 EST 2014-01-02 02:18:13.253154086 -0500 EST
2014-01-02 02:21:43.814198198 -0500 EST