om

om - the most recently modified file in a directory
git clone git://git.larryhynes.net/om
Log | Files | Refs | README

commit 6dc620fafc80e64491b4c73c4b8489917cddc25a
parent 1d5faf23407b5694d2f5694cc2ab7526e99680ee
Author: Larry Hynes <larry@larryhynes.com>
Date:   Sun,  2 Jul 2017 13:27:10 +0100

Refactor, fix and improve

- Use the correct prototype for snprintf
- Check for, and remove, a trailing slash on arg
- Hackish check() for empty rcnt (e.g. a dir of dirs),
  which is better than nothing, and can be improved
- exit(0); in main(), instead of return
- change 'directory' to 'd' (it's just shorter) in om()

Diffstat:
om.c | 37++++++++++++++++++++++++++++++-------
1 file changed, 30 insertions(+), 7 deletions(-)

diff --git a/om.c b/om.c @@ -24,25 +24,35 @@ isadir() } } +/* Check for, and remove, trailing slash on argument */ +char +*strip() +{ + size_t len=strlen(dir); + if((len > 0) && (dir[len-1] == '/')) + dir[len-1] = '\0'; + return dir; +} + char buf[PATH_MAX]; char rcnt[PATH_MAX]; void -om(const char* directory, char* rcnt) +om(const char* d) { DIR *dirp; struct dirent *ent; struct stat sb; time_t mtime = 0; - dirp = opendir(directory); + dirp = opendir(d); if (dirp != NULL) { while ((ent = readdir(dirp)) != NULL) { if (ent->d_type == DT_REG) { - snprintf(buf, PATH_MAX, "%s/%s", directory, ent->d_name); + snprintf(buf, sizeof(buf), "%s/%s", d, ent->d_name); stat(buf, &sb); if (sb.st_mtime > mtime) { - snprintf(rcnt, PATH_MAX, "%s/%s", directory, ent->d_name ); + snprintf(rcnt, sizeof(rcnt), "%s/%s", d, ent->d_name ); mtime = sb.st_mtime; } } @@ -51,10 +61,20 @@ om(const char* directory, char* rcnt) closedir(dirp); } else { - errx(1, "Could not open %s", directory); + errx(1, "Could not open %s", d); } } +/* If rcnt is empty e.g. argument is a dir of dirs, exit */ +int +check() +{ + size_t len=strlen(rcnt); + if(len == 0) + exit(0); + return 0; +} + int main(int argc, char *argv[]) { @@ -67,10 +87,13 @@ main(int argc, char *argv[]) } isadir(); + strip(); - om(dir, rcnt); + om(dir); + + check(); printf("%s\n", rcnt); - return 0; + exit(0); }