Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a file's ctime, atime, mtime and change them

Tags:

file

go

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

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

like image 828
user2368777 Avatar asked Jan 02 '14 02:01

user2368777


People also ask

What is the difference between mtime and ctime?

Modified timestamp (mtime): which is the last time a file's contents were modified. Change timestamp (ctime): which refers to the last time some metadata related to the file was changed.

How do I change ctime?

To modify ctime, you'll have to do something to the inode, such as doing a chmod or chown on the file. Changing the file's contents will necessarily also update ctime, as the atime/mtime/ctime values are stored in the inode. Modifying mtime means ctime also gets updated. Thanks for the feedback.

Does ls show mtime or ctime?

The simplest way to confirm the times associated with a file is to use ls command. This is the default output of ls -l, which shows you the time of the last file modification – mtime.


1 Answers

Linux

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.

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.

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)
}

Output:

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
like image 63
peterSO Avatar answered Oct 05 '22 11:10

peterSO