Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
Compare two times in C

How do I compare time in C? My program is getting the last modified time of 2 files, then compare that time to see which time is the latest. Is there a function that compares time for you, or you have to 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));
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Use difftime(time1, time0) from time.h to get the difference between two times. This calculates time1 - time0 and returns a double representing the difference in seconds. If it's positive, then time1 is later than time0; if negative, time0 is later; if 0, they're the same.

over 4 years ago · Santiago Trujillo Relatório

0

You can compare two time_t values to find which is newer:

#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, then you need to use difftime() officially, but in practice you can simply subtract the two time_t values.

over 4 years ago · Santiago Trujillo Relatório

0

You can use below method

double difftime (time_t end, time_t beginning);

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda