首页 > 解决方案 > 在 Linux 中使用 stat & tm structor 获取文件时间

问题描述

我在 linux 上使用 g++ 和 eclipse。我正在制作一个获取文件时间和输出文件月份、小时等的代码......

调试时,值time1意外更改,但我不知道这个问题。

这段代码有什么问题?

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


struct stat stat1, stat2;
struct tm *time1, *time2;

void filestat1(void);
void filestat2(void);
void filetime1(void);
void filetime2(void);
void datecmp(void);
void timecmp(void);

int main(void)
{
    filestat1();
    filestat2();
    filetime1();
    filetime2();
    datecmp();
    timecmp();
}

void filestat1(void)
{
    // check if there is no text1
    int check = 0;
    check = stat("text1", &stat1);    

    if(check != 0)
    {
        printf("Error : there is no text1\n");
    }
    return;
}


void filestat2(void)
{
    // check if there is no text2
    int check = 0;
    check = stat("text2", &stat2);    

    if(check != 0)
    {
        printf("Error : there is no text2\n");
    }
    return;
}


void filetime1(void)
{
    time1 = localtime(&stat1.st_mtime); //!!! this change unexpectedly
    return;
}


void filetime2(void)
{
    time2 = localtime(&stat2.st_mtime);    

    return;
}    

void datecmp(void)
{
    printf("date compare\n");
    // compare tm_mon
    if(time1->tm_mon > time2->tm_mon)
        printf("time1 is early \n");
    else if(time1->tm_mon < time2->tm_mon)
        printf("time2 is early \n");
    else{
        // compare tm_mday
        if(time1->tm_mday > time2->tm_mday)
            printf("time1 is early \n");
        else if(time1->tm_mday < time2->tm_mday)
            printf("time2 is early \n");
        // same date
        else
            printf("same time \n");
        }
        printf("\n");
}


void timecmp(void)
{

printf(time1->tm_hour);
printf(time2->tm_hour);
printf("time compare\n");
// compare hour
if(time1->tm_hour > time2->tm_hour)
    printf("time1 is early \n");
else if(time1->tm_hour < time2->tm_hour)
    printf("time2 is early \n");
else{
    // compare minutes
    if(time1->tm_min > time2->tm_min)
        printf("time1 is early \n");
    else if(time1->tm_min < time2->tm_min)
        printf("time2 is early \n");
    // same time
    else
        printf("same time \n");

    }
}

标签: clinuxstatlocaltime

解决方案


localtime返回指向静态结构的指针。您需要在localtime再次调用之前复制结果。

我会将time1and声明time2为结构而不是存储值的指针。

struct tm time1, time2;

void filetime1(void)
{
    struct tm *tmp = localtime(&stat1.st_mtime);
    if (tmp == NULL) {
        //... handle error
    }
    time1 = *tmp;
}

同样对于filetime2

如果您正在编写多线程代码,使用函数的可重入变体localtime_r. 在这种情况下,您将指针传递给结果结构。

void filetime1(void)
{
    struct tm *tmp = localtime_r(&stat1.st_mtime, &time1);
    if (tmp == NULL) {
        //... handle error
    } else {
        assert(tmp == &time1);
    }
}

推荐阅读