使用目录相关函数以及文件属性相关函数实现:显示指定路径下所有文件属性的功能(除了隐藏文件)
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<grp.h>
#include<pwd.h>
#include<time.h>
#include<errno.h>
#include<dirent.h>
#include<string.h>
int mode_get(int mode)
{
int b,c;
c = 1;
for(int i=8;i>=0;i--)
{
b = mode;
if(((b>>i)&c)==1)
{
if((i==2)||(i==5)||(i==8))
{
printf("r");
}
if((i==1)||(i==4)||(i==7))
printf("w");
if((i==0)||(i==3)||(i==6))
printf("x");
}
if(((b>>i)&c)==0)
{
printf("-");
}
}
}
int inode_file(int mode)
{
switch(mode & S_IFMT)
{
case S_IFSOCK:
printf("s");
break;
case S_IFLNK:
printf("l");
break;
case S_IFREG:
printf("-");
break;
case S_IFBLK:
printf("b");
break;
case S_IFDIR:
printf("d");
break;
case S_IFCHR:
printf("c");
break;
}
}
int get_username(uid_t uid)
{
struct passwd * user = getpwuid(uid);
printf("%s",user->pw_name);
}
int get_groutname(gid_t gid)
{
struct group* group = getgrgid(gid);
printf("%s",group->gr_name);
}
void get_size(long int size)
{
printf("%5ld",size);
}
void get_time(long int time)
{
struct tm*p = NULL;
p = localtime(&time);
printf("%d-%02d %02d %02d:%02d",p->tm_year+1900,p->tm_mon+1,p->tm_mday\
,p->tm_hour,p->tm_min);
}
int main(int argc, const char *argv[])
{
int num=0;
char name[20];
char filename[20];
if(argc>2)
{
printf("输入错误\n");
return -1;
}
DIR * dp = opendir(argv[1]);
if(dp == NULL)
{
perror("opendir");
return -1;
}
struct dirent * rp = NULL;
while(1)
{
bzero(name,sizeof(name));
bzero(filename,sizeof(filename));
rp = readdir(dp);
if(NULL == rp)
{
if(0 == errno)
{
printf("目录读取完毕\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
if(*(rp->d_name)!='.')
{
strcpy(name,rp->d_name);
num++;
strcat(filename,argv[1]);
strcat(filename,name);
int a;
struct stat buf;
if(stat(filename,&buf)<0)
{
perror("stat");
return -1;
}
a = buf.st_mode;
// printf("%o\n",a);
inode_file(a);
mode_get(a);
putchar(' ');
printf("%ld",buf.st_nlink);
putchar(' ');
get_username(buf.st_uid);
putchar(' ');
get_groutname(buf.st_gid);
putchar(' ');
get_size(buf.st_size);
putchar(' ');
get_time(buf.st_ctime);
putchar(' ');
printf("%s",name);
putchar(10);
}
}
return 0;
}
结果演示: