要点在于,跟ls -l的显示格式一致
#include<dirent.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
#include<string.h>
int main(int argc,char *argv[])
{
struct tm *tm;
struct group * grp;
struct passwd *pwd;
struct stat sb;
DIR *d;
struct dirent * dir;
char buf[1024];
ssize_t len;
// d=opendir(".");
if(argc>1){
printf("%s\n\n",argv[1]);
d=opendir(argv[1]);
}else{
d=opendir(".");
}
if(d)
{
// printf("d!=null\n");
while((dir=readdir(d))!=NULL)
{
//直接读的话会出现 . 和 ..,要去掉这两个
if(!strcmp(dir->d_name,".")||!strcmp(dir->d_name,"..")) continue;
// printf("%s\n",dir->d_name);
if(lstat(dir->d_name,&sb)!=-1)
{
printf( (S_ISDIR(sb.st_mode)) ? "d" : "-");
printf( (sb.st_mode & S_IRUSR) ? "r" : "-");
printf( (sb.st_mode & S_IWUSR) ? "w" : "-");
printf( (sb.st_mode & S_IXUSR) ? "x" : "-");
printf( (sb.st_mode & S_IRGRP) ? "r" : "-");
printf( (sb.st_mode & S_IWGRP) ? "w" : "-");
printf( (sb.st_mode & S_IXGRP) ? "x" : "-");
printf( (sb.st_mode & S_IROTH) ? "r" : "-");
printf( (sb.st_mode & S_IWOTH) ? "w" : "-");
printf( (sb.st_mode & S_IXOTH) ? "x" : "-");
printf(" %d ",sb.st_nlink);
pwd=getpwuid(sb.st_uid);
grp=getgrgid(sb.st_gid);
//获取文件所属用户名、所属组名,文件大小
printf("%s %s %d ",pwd->pw_name,grp->gr_name,sb.st_size);
//根据时间戳获取世间
tm=localtime(&sb.st_mtime);
//格式化时间
printf("%d月 %d %d:%d %s",tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,basename(dir->d_name));
//如果是link类型的文件,还得模拟ls -l显示其真实位置!
if((S_IFMT & sb.st_mode)==S_IFLNK){
if((len=readlink(dir->d_name,buf,sizeof(buf)-1))!=-1)
{
buf[len]='\0';}
printf("->%s",buf);
}
printf("\n");
}
}
closedir(d);
}
return 0;
}