1753507 Members
5005 Online
108795 Solutions
New Discussion юеВ

Re: C code required.

 
SOLVED
Go to solution
Nigel Green
Advisor

C code required.


Any of you C guru's out there got a nifty piece of code that will return the name of the oldest file or directory in the current directory?

Im not looking for a system call!
7 REPLIES 7
Pete Randall
Outstanding Contributor

Re: C code required.

How about ls -u | head?


Pete

Pete
Pete Randall
Outstanding Contributor

Re: C code required.

Or ls -lc |head?


Pete


Pete
Hoefnix
Honored Contributor

Re: C code required.

what about next:
ls -alrt | grep -v total | head -1 | awk '{ print $9 }'

This wil also return ".filenames"

(why use C)
G. Vrijhoeven
Honored Contributor

Re: C code required.

Hi,

Pete is right, just use ls:

ls -lt is an other option.

Gideon
Elmar P. Kolkman
Honored Contributor
Solution

Re: C code required.

In C it will have to be a combo of stat(2) and the directory(3C) calls, I think. I haven't tried the code below, but it should work, according to the manpages:

#include
#include
#include

void main() {
int old_time=-1;
char old_name[MAXNAMLEN+1] = "";
DIR *dirp;
struct dirent *dp;
struct stat stb;

dirp = opendir(".");
while ((dp = readdir(dirp)) != NULL) {
stat(dp->d_name,&stb);

if ((old_time > stb.st_ctime) || (old_time==-1)){
old_time = stb.st_ctime;
strcpy(old_name,dp->d_name);
}
}
printf("Oldest file: %s\n",old_name);
}
Every problem has at least one solution. Only some solutions are harder to find.
Nigel Green
Advisor

Re: C code required.

Thanks for the replies.
Mister_Z
Frequent Advisor

Re: C code required.

you can create the following script (not necessary to develop any C code).

ls -lt $1 | tail -1

name this script lsoldest, for instance, and give execute perimissions. After copying it to /usr/sbin or any other directory included in the path you can use

#lsoldest

to obtain a full listing for the oldest file/directory under
I work for HP