c - 获取目录 C 中最旧的文件

标签 c linux

我问过一个关于在目录中获取最新文件的类似问题,我得到了这个我非常喜欢的答案:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <ftw.h>

char newest[PATH_MAX];
time_t mtime = 0;

int checkifnewer(const char *path, const struct stat *sb, int typeflag)
{
    if (typeflag == FTW_F && sb->st_mtime > mtime) {
        mtime = sb->st_mtime;
        strncpy(newest, path, PATH_MAX);
    }
    return 0;
}

main()
{
    ftw("./example", checkifnewer, 1); 
    printf("%s\n", newest);
}

我想使用该函数来获取我试图更改条件的目录中最旧的文件:

 if (typeflag == FTW_F && sb->st_mtime > mtime)

 if (typeflag == FTW_F && sb->st_mtime < mtime)

程序不会崩溃或给出任何结果,知道如何做到这一点! 感谢@Mark Plotnick 的回答

最佳答案

您需要处理启动条件。您可以尝试将 mtime 的值初始化为一个非常高的数字,但由于技术原因,很难可靠地预测它可能是什么。最佳初始值只是搜索中的第一个值,一种方便的方法是初始化为零并将其作为特殊情况处理。这是一个通用的编程技巧,值得记住。

char newest[PATH_MAX+1] = {0};
time_t mtime = 0;
int check_if_older(const char *path, const struct stat *sb, int typeflag) {
    if (typeflag == FTW_F && (mtime == 0 || sb->st_mtime < mtime)) {
        mtime = sb->st_mtime;
        strncpy(newest, path, PATH_MAX+1);
    }
    return 0;
}

我还做了另外两项更改。看看你是否能找出原因。

关于c - 获取目录 C 中最旧的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382163/

相关文章:

.net 核心异步/等待 tcp 与 linux

c - 在 linux 上用 C 语言销毁信号量时如何防止错误?

c - 是否有 libc 函数(或等效函数)可以知道堆的当前大小?

c - 如何使用 statx 系统调用?

c - GCC header 搜索路径已弃用

linux - perl dbi :odbc crashing/using strange file

c - C中的动态大小数组

C 平方时答案错误

c++ - 为什么 linux 在分配动态内存时会占用一些额外的空间?

Linux 内核架构支持时间表