简体   繁体   English

从上次在OS X中使用C修改文件以来获得时间?

[英]Getting time since file was last modified in OS X using C?

I have the following code that is suppose to print time passed since file was last modified: 我有以下代码假定打印自文件上次修改以来经过的时间:

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

    struct stat fileInfo;
    char * dir = "/Users/jenna/Desktop/Random.rtf";
    stat(dir, &fileInfo);

    printf("Last modified time: %s\n", ctime(&fileInfo.st_mtime));

    time_t mytime;
    mytime = time(NULL);
    printf("Current time: %s\n", ctime(&mytime));

    double diff = difftime(ctime(&mytime), ctime(&fileInfo.st_mtime));
    printf("diff : %f\n", diff);

}

Unfortunately, this code gives the following output: 不幸的是,这段代码给出了以下输出:

Last modified time: Wed Apr  6 00:15:30 2016

Current time: Wed Apr  6 00:17:29 2016

diff : 0.000000

When I change the format flag in the printf to %d , I get the following output: 当我将printf中的格式标志更改为%d ,得到以下输出:

Last modified time: Wed Apr  6 00:15:30 2016

Current time: Wed Apr  6 00:18:34 2016

diff : 1983419808

Neither output is correct since I am expecting the difference of just several minutes( expressed in seconds). 两种输出都不正确,因为我期望只有几分钟的差异(以秒表示)。 What am I doing wrong here ? 我在这里做错了什么? Thanks for any help. 谢谢你的帮助。

You should get into the practise of enabling compiler warnings. 您应该开始启用编译器警告的实践。 This code should be giving you some very helpful ones. 此代码应为您提供一些非常有用的代码。 Specifically, you're passing char* values into difftime . 具体来说,您要将char*值传递给difftime

Since ctime always returns a pointer to the same static memory, the two calls to ctime return the same pointer. 由于ctime总是返回指向相同静态内存的指针,因此两次调用ctime返回相同的指针。 Now you are implicitly casting these to time_t (compiler warning!!!), and you get a difference of zero. 现在,您将它们隐式转换为time_t (编译器警告!!!),并且您得到的差为零。

In the second case, you pass a double into printf and tell it you passed an int , which is undefined behaviour. 在第二种情况下,将double传递给printf并告诉它传递了int ,这是未定义的行为。

What you actually want is to pass time_t values into difftime like this: 真正想要的是将time_t值传递给difftime如下所示:

double diff = difftime( mytime, fileInfo.st_mtime );
printf( "diff : %f\n", diff );

And get into the habit of reading documentation for functions that you are unfamiliar with: 并养成阅读文档的功能,这些功能是您不熟悉的:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM