【问题标题】:Getting file time using stat & tm structor in Linux在 Linux 中使用 stat & tm structor 获取文件时间
【发布时间】:2018-04-27 16:24:55
【问题描述】:

我在 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");

    }
}

【问题讨论】:

  • 虽然你最初标记并提到g++,但你的代码是C,而不是C++,所以我调整了标签。

标签: c linux stat localtime


【解决方案1】:

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

我会将time1 和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);
    }
}

【讨论】:

  • filetime 函数可以吗?可以用吗?
  • ../main.c:87: filetime2: 断言tmp == &amp;time1 失败。我加入了assert.h,但它不起作用。
  • filetime2 应该使用time2,即使在断言中也是如此。
  • 哦.. 抱歉我错过了。我会改的
  • 我正在尝试使用您的建议2,但我输出错误。 ../main.c:87: filetime2: 断言 `tmp == &time2' 失败。另外,在调试的时候,time1和time2不能取值。
【解决方案2】:

您完全不必要地使用全局变量,这让您的生活变得更加艰难。我们人类很难跟踪全局变量的修改位置,尤其是当您有多个名称非常相似的全局变量时。

所以,与其试图解开这一切,不如让我们使用函数参数重写它,根本不使用任何全局变量。

首先,我们告诉 C 库我们想要 POSIX.1-2008 功能,并包含公开我们需要的功能的标头:

#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <limits.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

接下来,让我们定义一个以文件名作为参数的函数,以及指向函数可以存储上次访问和上次修改时间戳的位置的指针。如果函数成功,则返回0;否则,它将返回 -1 并设置 errno 以指示错误。

int filetime(const char *path,
             time_t *accessed, long *accessed_nsec,
             time_t *modified, long *modified_nsec)
{
    struct stat  info;

    /* Path must not be NULL or empty. */
    if (!path || !path[0]) {
        errno = EINVAL;
        return -1;
    }

    /* Get file statistics. */
    if (stat(path, &info) == -1)
        return -1; /* errno was set by stat() */

    /* Save timestamps. */
    if (accessed)
        *accessed = info.st_atim.tv_sec;
    if (accessed_nsec)
        *accessed_nsec = info.st_atim.tv_nsec;
    if (modified)
        *modified = info.st_mtim.tv_sec;
    if (modified_nsec)
        *modified_nsec = info.st_mtim.tv_nsec;

    /* Success. */
    return 0;
}

让我们继续编写一个简单的main(),它将一个或多个文件名作为命令行参数,并对其进行描述。我喜欢通过检查命令行参数的数量以及第一个参数(如果指定)来启动 main。如果没有,或者第一个是-h 或--help,我喜欢打印该实用程序的使用情况。这样,我可以将示例程序保存在它们自己的目录中,并且要找到我正在寻找的一个,我可以不带参数地执行每个示例程序,以查看它们各自的作用。这比阅读源代码要快得多!

int main(int argc, char *argv[])
{
    int arg;

    if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
        fprintf(stderr, "\n");
        fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv[0]);
        fprintf(stderr, "       %s FILENAME ...\n", argv[0]);
        fprintf(stderr, "\n");
        fprintf(stderr, "This program will print the last access and\n");
        fprintf(stderr, "last modification timestamps for each of\n");
        fprintf(stderr, "the specified files.\n");
        fprintf(stderr, "\n");
        return EXIT_FAILURE;
    }

因为至少有一个,但可能不止一个文件名参数,我们在一个循环中处理它们中的每一个:

    for (arg = 1; arg < argc; arg++) {
        time_t     accessed, modified;
        long       accessed_ns, modified_ns;
        struct tm  accessed_localtime, modified_localtime;

在循环中,我们首先调用filetime() 函数。请注意我们如何在上面声明我们想要填充的变量,以及我们如何调用函数:&amp;accessed 产生一个指向 accessed 的指针。

        if (filetime(argv[arg], &accessed, &accessed_ns,
                                &modified, &modified_ns)) {
            /* Nonzero return value, so an error occurred! */
            fprintf(stderr, "%s: %s.\n", argv[arg], strerror(errno));
            return EXIT_FAILURE;
        }

在 C 中,函数参数是按值传递的,而不是按引用传递的。这意味着如果函数参数是 int foo,则函数内对 foo 的任何更改仅在函数内可见;调用者看不到更改。当我们传递一个指向变量的指针时,比如int *foo,然后更改为foo 仍然只在函数内可见,但*foo 指的是指针指向的值;并且对的更改对调用者可见。

简而言之,当我们希望函数能够修改变量的值时,我们使用指针。这就是 C 的工作原理。

现在我们有了 Unix Epoch 时间 (time_t) 的时间,我们想将它们拆分为本地时间字段:

        if (!localtime_r(&accessed, &accessed_localtime) ||
            !localtime_r(&modified, &modified_localtime)) {
            fprintf(stderr, "%s: Cannot compute timestamps in local time: %s.\n", argv[arg], strerror(errno));
            return EXIT_FAILURE;
        }

请注意,我再次使用了 POSIX.1-2008 函数 localtime_r()。在教程中,您经常会看到使用较旧的localtime(),但它可能会在内部使用全局变量(它总是可以返回指向同一结构的指针,每次调用都重用它); localtime_r() 更好。

看看localtime_r 的第二个参数如何也是一个指针(指向struct tm)?同样,这就是您执行以调用者可见的方式更改某些值的函数的方式。

另外,localtime_r()(或localtime())很少会失败,所以很多人只是忽略了检查它是否有错误。没有任何借口,因为它只是多了几行代码,如果在某个时候确实发生了错误,用户将对清晰的错误代码感到非常满意,而不仅仅是看到程序由于分段而崩溃故障。

剩下的就是打印收集到的信息。我喜欢使用ISO 8601 国际标准时间格式的变体;特别是,即使按字母顺序排序,它也会按正确的时间顺序排序。 (我的变种是我喜欢在日期和时间之间使用空格,而不是 T。)

        printf("%s:\n", argv[arg]); /* The file name or path */

        printf("    Modified: %04d-%02d-%02d %02d:%02d:%02d.%03d\n",
               modified_localtime.tm_year + 1900,
               modified_localtime.tm_mon + 1,
               modified_localtime.tm_mday,
               modified_localtime.tm_hour,
               modified_localtime.tm_min,
               modified_localtime.tm_sec,
               modified_ns / 1000000L);

        printf("    Accessed: %04d-%02d-%02d %02d:%02d:%02d.%03d\n",
               accessed_localtime.tm_year + 1900,
               accessed_localtime.tm_mon + 1,
               accessed_localtime.tm_mday,
               accessed_localtime.tm_hour,
               accessed_localtime.tm_min,
               accessed_localtime.tm_sec,
               accessed_ns / 1000000L);

        /* Make sure everything written to stdout
           is actually written to standard output right now. */
        fflush(stdout);
    }

    return EXIT_SUCCESS;
}

fflush(stdout) 告诉 C 库确保之前对stdout 的所有写入都实际写入标准输出。 (默认情况下,stdout 是缓冲的,stderr 是非缓冲的。)通常情况下,C 库会在每个换行符处刷新输出,但是在那里显式刷新也会提醒我们人类程序员,我们想要打印到目前为止的所有内容,到那时实际出现在程序标准输出中。 (这样,如果其中一个文件位于某个慢速文件系统上,例如旧的 USB 记忆棒或网络共享,则在程序访问慢速文件之前会显示有关先前文件的信息。基本上,“停顿”将发生在预期的人类用户的地方。)

此时提及relatime 和其他相关的挂载选项可能是个好主意。简单来说,就是为了避免由于读访问导致对存储介质的写入次数,访问时间并不总是更新。因此,如果即使在您读取文件后(例如使用 cat FILENAME &gt;/dev/null)您也没有看到它发生变化,这仅意味着您的系统启用了挂载选项,以减少访问时间更新以加快文件系统访问并减少写给它。这是一个不错的选择;我用它。

最后,大多数 Linux 文件系统根本没有 created 时间戳。 st_ctime(以及st_ctim.tv_sec 和st_ctim.tv_nsec)字段指的是上次状态更改时间戳。它跟踪所有者、组、权限和硬链接数量的变化。

当您检查上述代码时,尤其是 if 子句时,记住在 C 中逻辑 OR 操作 || 是短路的:首先计算左侧,但如果它失败,则根本不评估右侧。所以,如果你有例如int x = 1, y = 0; 和 (x == 0 || ++y),y 根本不会增加。我在main() 的第一个if 子句中检查argv[1] 时使用了这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    相关资源
    最近更新 更多