Friday, March 6, 2009

latest.c

After having learned a lot about how to manipulate files in my past endeavor, I've decided to reimplement latest.sh in C:

latest.c

#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#define MAX_FLEN 256



int main(int argc, const char ** argv) {
struct {
time_t value;
char name[MAX_FLEN];
} tval = {0, ""};
struct stat info;
DIR * dirinfo;
struct dirent * file;
size_t i;
if(argc > 1) {
for(i = 1; i < argc; i++) {
if(!stat(argv[i], &info)) {
if(!*tval.name || info.st_mtime > tval.value) {
tval.value = info.st_mtime;
strncpy(tval.name, argv[i], MAX_FLEN);
}
}
else
perror(argv[i]);
}
}
else {
dirinfo = opendir(".");
while((file = readdir(dirinfo)) != NULL) {
if(file->d_name[0] != '.') {
if(!stat(file->d_name, &info)) {
if(!*tval.name || info.st_mtime > tval.value) {
tval.value = info.st_mtime;
strncpy(tval.name, file->d_name, MAX_FLEN);
}
}
else
perror(file->d_name);
}
}
closedir(dirinfo);
}
if(*tval.name) {
tval.name[MAX_FLEN - 1] = '\0';
puts(tval.name);
return 0;
}
else
return 1;
}

It simply finds the file with the most recent modification time.

Post a Comment