Reputation: 2100
I'm trying to write a portable function in c that compares the last modified times of 2 files. The files are tiny and written one right after the other, so I need finer granularity than 1 second (milliseconds).
There seems to be a plethora of time/date functions...
Upvotes: 3
Views: 5873
Reputation:
The C standard does not have any functions for this, but the Posix specification does. The 2008 edition even provides sub-second timestamps. #define _POSIX_C_SOURCE 200809L
The following code should give you an idea how to use it.
#define _POSIX_C_SOURCE 200809L
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h> // for printf
#include <stdlib.h> // for EXIT_FAILURE
int main(int argc, char **argv)
{
for (int i = 1; i < argc; ++i) {
struct stat st = {0};
int ret = lstat(argv[i], &st);
if (ret == -1) {
perror("lstat");
return EXIT_FAILURE;
}
printf("%s: mtime sec=%lld nsec=%lld\n", argv[i],
(long long) st.st_mtim.tv_sec,
(long long) st.st_mtim.tv_nsec);
}
return 0;
}
Upvotes: 2
Reputation: 16389
For POSIX UNIX, stat()
is portable and gives struct stat st_mtime
which is the modification time in epoch seconds. Windows stat returns windows time values, and has creation time rather than st_ctime
.
For non-POSIX UNIX implementations, Windows and other OSes there is no portable concept of file modification time. So, depending on your idea of portable, this whole concept may or my not work for you.
Upvotes: 1
Reputation: 5637
You should look to the stat()
function. It's available on *nix and on windows.
They will both return you a struct containing a field name st_msize. They are the finest functions I have heard of in order to get this kind of information from an Operating System.
Since you need portability, beware to take care of the various different types available on Windows. On *NIX, it's a classic time_t structure. If you include specific call, you can obtain nano seconds mtime: it was defined in POSIX.1-2008, according to the man page.
You can also take a look at how you can deal with 64/32 bit time_t
Upvotes: 3