om

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

commit faf4c05b481f29a642fd9bbd3409a87409dca2fb
parent 21794a4e177fa1c26340343d037c315edba49278
Author: Larry Hynes <larry@larryhynes.com>
Date:   Mon,  3 Jul 2017 11:00:56 +0100

Another cleanup

- Don't specify gcc as cc in Makefile
- Work around gcc-7 warning
- Tidy up

Diffstat:
om.c | 78++++++++++++++++++++++++++++++++++++++++++------------------------------------
1 file changed, 42 insertions(+), 36 deletions(-)

diff --git a/om.c b/om.c @@ -8,13 +8,15 @@ #include <string.h> char *dir; +char buf[PATH_MAX +1]; +char res[PATH_MAX]; -/* Test if the argument is a directory */ +/* Test if argument can be stat-ed, and is a directory */ int -isadir() +isdir() { - struct stat sb; - if (stat(dir, &sb) == 0 && S_ISDIR(sb.st_mode)) + struct stat st; + if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode)) { return 0; } @@ -26,55 +28,60 @@ isadir() /* Check for, and remove, trailing slash on argument */ char -*strip() +*strp() { - size_t len=strlen(dir); - if((len > 0) && (dir[len-1] == '/')) - dir[len-1] = '\0'; + 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* d) +om() { DIR *dirp; struct dirent *ent; - struct stat sb; time_t mtime = 0; + struct stat sb; - dirp = opendir(d); - if (dirp != NULL) { - while ((ent = readdir(dirp)) != NULL) { - if (ent->d_type == DT_REG) { - snprintf(buf, sizeof(buf), "%s/%s", d, ent->d_name); - stat(buf, &sb); - if (sb.st_mtime > mtime) { - snprintf(rcnt, sizeof(rcnt), "%s/%s", d, ent->d_name ); - mtime = sb.st_mtime; - } + dirp = opendir(dir); + if (!dirp) + return; + + while ((ent = readdir(dirp)) != NULL) { + snprintf(buf, sizeof(buf), "%s/%s", dir, ent->d_name); + stat(buf, &sb); + if(S_ISREG(sb.st_mode)) { + stat(buf, &sb); + if (sb.st_mtime > mtime) { + snprintf(res, sizeof(res), "%s", ent->d_name ); + mtime = sb.st_mtime; } } + } - closedir(dirp); + closedir(dirp); - } else { - errx(1, "Could not open %s", d); - } } -/* If rcnt is empty e.g. argument is a dir of dirs, exit */ +/* If res is empty e.g. argument is a dir of dirs, exit */ int -check() +chck() { - size_t len=strlen(rcnt); + size_t len=strlen(res); if(len == 0) exit(0); return 0; } +void +prnt(char *d, char *f) +{ + fputs(d, stdout); + putchar('/'); + puts(f); +} + int main(int argc, char *argv[]) { @@ -86,14 +93,13 @@ main(int argc, char *argv[]) errx(1, "Usage: %s directory", argv[0]); } - isadir(); - strip(); + isdir(); + strp(); om(dir); - check(); - printf("%s\n", rcnt); - - exit(0); + chck(); + prnt(dir, res); + return 0; }