1.要求输入目录的路径后,能够打印出指定路径下所有文件的详细信息,类似ls -l
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <dirent.h>
#include <errno.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>
//文件权限
void get_filePermission(mode_t m)
{
for(int i=0;i<9;i++)
{
if(((0400>>i)&m)==0)
{
putchar('-');
continue;
}
//判断打印是r w x
switch(i%3)
{
case 0:
putchar('r');
break;
case 1:
putchar('w');
break;
case 2:
putchar('x');
break;
}
}
}
//文件类型
void get_fileType(mode_t m)
{
switch(m&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('p'); break;
case S_IFLNK: putchar('l'); break;
case S_IFSOCK: putchar('s'); break;
default: printf("mode错误\n");
}
}
//文件所属用户
void get_fileUsrname(uid_t uid)
{
struct passwd* pwd = getpwuid(uid);
if(NULL==pwd)
{
perror("pwd");
return;
}
printf(" %s ",pwd->pw_name);
}
//文件所属组用户
void get_fileGrpname(gid_t gid)
{
struct group* grp = getgrgid(gid);
if(NULL==grp)
{
perror("getgrgid");
return;
}
printf("%s ",grp->gr_name);
}
//文件的时间
void get_filetime(struct stat buf)
{
struct tm* info=NULL;
info=localtime(&buf.st_ctime);
char *s=NULL;
int i=info->tm_mon+1;
switch(i)
{
case 1: s="一月"; break;
case 2: s="二月"; break;
case 3: s="三月"; break;
case 4: s="四月"; break;
case 5: s="五月"; break;
case 6: s="六月"; break;
case 7: s="七月"; break;
case 8: s="八月"; break;
case 9: s="九月"; break;
case 10: s="十月"; break;
case 11: s="十一月"; break;
case 12: s="十二月"; break;
}
printf("%s %d %d:%02d",s,info->tm_mday,\
info->tm_hour,info->tm_min);
}
int main(int argc, const char *argv[])
{
//判断输入参数是否正确
if(argc <2)
{
perror("格式不规范");
return -1;
}
//打开目录
DIR* dp =opendir(argv[1]);
if(NULL == dp)
{
perror("opendir");
return -1;
}
printf("目录文件打开成功\n");
struct dirent* rp = NULL;
while(1)
{
rp = readdir(dp);
if(NULL == rp)
{
if(0 == errno)
{
printf("读取到目录结尾\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
if(*(rp->d_name)=='.')
{
continue;
}
//获取文件的属性
struct stat buf;
if(stat(rp->d_name,&buf)<0)
{
perror("stat");
return -1;
}
//文件的类型以及文件权限
get_fileType(buf.st_mode);
get_filePermission(buf.st_mode);
//文件硬链接数
printf(" %2ld ",buf.st_nlink);
//文件所属用户
get_fileUsrname(buf.st_uid);
//文件所属组用户
get_fileGrpname(buf.st_gid);
//文件的大小
printf(" %6ld ",buf.st_size);
//文件的时间
get_filetime(buf);
//文件名
printf(" %s \n",rp->d_name);
}
//关闭目录
if(closedir(dp) < 0)
{
perror("closedir");
return -1;
}
return 0;
}