|
楼主 |
发表于 2004-7-25 11:21:36
|
显示全部楼层
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#define BLKSIZE 1024
char *get_perms(struct stat *sbuf,char *perms)
{
static char *modes[]={"---","--x","-w-","r--","r-x","rw-","rwx"};/* */
int i,j;
*perms='\0';
/* */
for(i=2;i>=0;i--){
j=(sbuf->st_mode>>(i*3))&07;
strcat(perms,modes[j]);
}
if((sbuf->st_mode &S_ISUID)!=0)
perms[2]='s';
if((sbuf->st_mode &S_ISGID)!=0)
perms[5]='s';
if((sbuf->st_mode &S_ISUID)!=0)
perms[8]='t';
return perms;
}
char *get_perms(struct stat *,char *);
void list(char *);
void printout(char *,char *);
int main(int argc,char *argv[])
{
struct stat sbuf;
if(argc<2){
list(".");
exit(0);
}
while(--argc){
if(stat(* ++argv,&sbuf)<0){
printf(*argv);
continue;
}
if((sbuf.st_mode &S_IFMT)==S_IFDIR)
list(*argv);
else
printout(".",*argv);
}
exit(0);
}
void list(char *name)
{
DIR *dp;
struct dirent *dir;
if((dp=opendir(name))==NULL){
fprintf(stderr,"%s:cannot open.\n",name);
exit(0);
}
while((dir=readdir(dp))!=NULL)
printout(name,dir->d_name);
closedir(dp);
return;
}
void printout(char *dir,char *name)
{
int i,j;
char perms[10];
struct stat sbuf;
char newname[BLKSIZE];
sprintf(newname,"%s/%s",dir,name);
stat(newname,&sbuf);
printf("%5d",(sbuf.st_size+BLKSIZE-1)/BLKSIZE);
switch(sbuf.st_mode &S_IFMT){
case S_IFREG:putchar('-');break;
case S_IFDIR:putchar('d');break;
case S_IFCHR:putchar('c');break;
case S_IFBLK:putchar('b');break;
case S_IFIFO:putchar('l');break;
#ifdef S_IFLNK
case S_IFLNK:putchar('l');break;
#endif
#ifdef S_IFSOCK
case S_IFSOCK:putchar('l');break;
#endif
default:putchar('?');break;
}
get_perms(&sbuf,perms);
printf("%s%3d%-5d",perms,sbuf.st_nlink,sbuf.st_uid,sbuf.st_gid);
printf("%7d %.20s",sbuf.st_size,ctime(&sbuf.st_mtime));
printf("%s\n",name);
} |
|