Compare two times in C

How do you compare times in C? My program gets the last modified time from 2 files and then compares that time to find out what is the last time. Is there a function that compares the time for you, or should you create one yourself? This is my get time function:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>

void getFileCreationTime(char *path) {
    struct stat attr;
    stat(path, &attr);
    printf("Last modified time: %s", ctime(&attr.st_mtime));
}

      

+3


source to share


4 answers


Use difftime(time1, time0)

from time.h

to get the difference between two values. This computes time1 - time0

and returns a double

representing the difference in seconds. If it is positive, it time1

will be greater than time0

; if negative, time0

later; if 0, then they are the same.



+5


source


You can compare the two values time_t

to find the newer one:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>

static time_t getFileModifiedTime(const char *path)
{
    struct stat attr;
    if (stat(path, &attr) == 0)
    {
        printf("%s: last modified time: %s", path, ctime(&attr.st_mtime));
        return attr.st_mtime;
    }
    return 0;
}

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s file1 file2\n", argv[0]);
        return 1;
    }
    time_t t1 = getFileModifiedTime(argv[1]);
    time_t t2 = getFileModifiedTime(argv[2]);
    if (t1 < t2)
        printf("%s is older than %s\n", argv[1], argv[2]);
    else if (t1 > t2)
        printf("%s is newer than %s\n", argv[1], argv[2]);
    else
        printf("%s is the same age as %s\n", argv[1], argv[2]);
    return 0;
}

      



If you want to know the difference between the values ​​in seconds, you need to officially use difftime()

, but in practice you can just subtract the two values time_t

.

+3


source


You can use below method

double difftime (time_t end, time_t beginning);

      

It returns the time difference in seconds. You can find an example here.

+2


source


my code:

char * findLeastFile(char *file1, char *file2){
    struct stat attr1, attr2;
    if (stat(file1, &attr1) != 0 || stat(file2, &attr2) != 0)
    {
        printf("file excetion");
        return NULL;
    }
    if(difftime(attr1.st_mtime,attr2.st_mtime) >= 0)
        return file1;
    else 
        return file2;

}

      

+1


source







All Articles