实现linux命令ls -l,
ls -l显示指定目录下的文件和子目录。可以显示文件的权限,大小,所有者,创建时间等。目录通过运行时参数传入。
代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
int main(int argc ,char *argv[])
{
struct stat buf;
char out[100];
if(argc == 1 )
{
fprintf(stderr,"Using %s
filename\n",argv[0]);
return 0;
}
if(lstat(argv[1],&buf)<0)
{
fprintf(stderr,"stat
error:%s\n",strerror(errno));
return -1;
}
switch(buf.st_mode &
S_IFMT)
{
case S_IFREG:
printf("-");
break;
case S_IFDIR:
printf("d");
break;
case S_IFCHR:
printf("c");
break;
case S_IFBLK:
printf("b");
break;
case S_IFIFO:
printf("p");
break;
case S_IFLNK:
printf("l");
break;
case S_IFSOCK:
printf("s");
break;
}
if(S_IRUSR &
buf.st_mode)
printf("r");
else
printf("-");
if(S_IWUSR & buf.st_mode)
printf("w");
else
printf("-");
if(S_IXUSR & buf.st_mode)
printf("x");
else
printf("-");
if(S_IRGRP & buf.st_mode)
printf("r");
else
printf("-");
if(S_IWGRP & buf.st_mode)
printf("w");
else
printf("-");
if(S_IXGRP & buf.st_mode)
printf("x");
else
printf("-");
if(S_IROTH & buf.st_mode)
printf("r");
else
printf("-");
if(S_IWOTH & buf.st_mode)
printf("w");
else
printf("-");
if(S_IXOTH & buf.st_mode)
printf("x");
else
printf("-");
printf(" %d",buf.st_nlink);
struct passwd *pw;
pw = getpwuid(buf.st_uid);
printf(" %s",pw->pw_name);
struct group *gr;
gr = getgrgid(buf.st_gid);
printf(" %s",gr->gr_name);
printf(" %ld",buf.st_size);
struct tm *t;
t =
localtime(&buf.st_atime);
printf(" %d-%d-%d
%d:%d",t->tm_year+1900,
t->tm_mon+1,
t->tm_mday,
t->tm_hour,
t->tm_min);
printf(" %s
",argv[1]);
if(S_ISLNK(buf.st_mode))
{
printf(" ->
");
if(readlink(argv[1],out,100)==-1)
{
}
printf("%s",out);
}
printf("\n");
return 0;
}
加载中,请稍候......