【问题标题】:Checking the modification date does not work [duplicate]检查修改日期不起作用[重复]
【发布时间】:2019-04-03 08:21:21
【问题描述】:

我在检查修改日期时遇到问题。 fprintf 在控制台中为文件夹中的每个文件打印相同的数字等于 0。

while (1) {
    source = opendir(argv[1]);
    while ((file = readdir(source)) != NULL) {
        if (file->d_type != DT_REG)
            continue; 
        stat(file->d_name, &file_details);
        fprintf(stderr, "Name: %s, Last modify: %ld  \n", file->d_name, file_details.st_mtime);
    }
    closedir(source);
    sleep(5);
}

【问题讨论】:

  • 错误检查!你没有。您需要添加它。我的猜测是 stat 返回 -1errno == ENOENT
  • 并提示我认为问题所在:file->d_name 只是文件名,而不是完整路径。
  • 如何获得完整路径?
  • @kamilm758 您必须通过连接目录名和文件名来构建它,当然,/ 介于两者之间。另一种方法是进入被扫描的目录,chdir().

标签: c linux daemon


【解决方案1】:

您必须构造目录条目的路径并将其传递给stat。您当前传递的条目名称,仅当您从当前目录枚举时才有效。

此外,您应该测试stat 的返回值以检测任何问题。这将表明 stat 使用当前代码失败。

这是修改后的版本:

#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

...

char path[1024];
while (1) {
    source = opendir(argv[1]);
    if (source == NULL)
        break;
    while ((file = readdir(source)) != NULL) {
        if (file->d_type != DT_REG)
            continue; 
        snprintf(path, sizeof path, "%s/%s", path, file->d_name);
        if (!stat(path, &file_details))
            fprintf(stderr, "Name: %s, Last modify: %ld\n", path, file_details.st_mtime);
        else
            fprintf(stderr, "Cannot stat %s; %s\n", path, strerror(errno));
    }
    closedir(source);
    sleep(5);
}

【讨论】:

  • 广告检查opendir 是否成功?
  • 如果修改日期较大,那么文件是后来修改的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多