Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display file last modification time on linux

Tags:

c

file

linux

time

I want to write a C program to display the file last modification time in microsecond or millisecond. How could I do? Could you give me a help?

Thanks very much.

like image 961
JavaMobile Avatar asked Feb 23 '11 02:02

JavaMobile


3 Answers

The stat() function is used. In sufficiently recent versions of glibc, st_mtim (note: no trailing e) is a field of type struct timespec that holds the file modification time:

struct stat st;

if (stat(filename, &st)) {
    perror(filename);
} else {
    printf("%s: mtime = %lld.%.9ld\n", filename, (long long)st.st_mtim.tv_sec, st.st_mtim.tv_nsec);
}

You should check for the presence of st_mtim in struct stat in your build system, and be ready to fall back to st_mtime (which has type time_t, and only 1 second resolution) if it is not present.

like image 178
caf Avatar answered Sep 28 '22 05:09

caf


You may use stat() function, it will return struct stat which contains time of last modification of a file. Here is the man page http://linux.die.net/man/2/stat. As to precision, it depends on whether your file system supports sub-second timestamps or not.

like image 34
ZelluX Avatar answered Sep 28 '22 05:09

ZelluX


JFS, XFS, ext4, and Btrfs support nanosecond timestamps.

The book "The Linux Programming Interface" by Michael Kerrisk has a good section on File attributes

like image 40
Matt Avatar answered Sep 28 '22 05:09

Matt