Reputation: 5422
I've asked a similar question about getting the newest file in directory and I've got this answer that I really like :
#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);
}
I want to use the function to get the oldest file in the directory for that I've tried to change the condition :
if (typeflag == FTW_F && sb->st_mtime > mtime)
to
if (typeflag == FTW_F && sb->st_mtime < mtime)
the program doesn't crash or give any result, any idea how to do this ! for the record thanks to @Mark Plotnick for his answer
Upvotes: 1
Views: 1615
Reputation: 10868
You need to handle the startup condition. You could try to initialise the value of mtime
to a very high number, but for technical reasons it's hard to reliably predict what that might be. The best initial value is simply the first value in the search and a convenient way to do that is to initialise to zero and handle that as a special case. This is a general programming technique, worth remembering.
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;
}
I've made two other changes. See if you can work out why.
Upvotes: 3