1.显示指定路径下所有文件的权限 硬链接数 时间 以及名字
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
void get_file(mode_t mode,char *p)
{
char per[]="rwx";
for(int i=0;i<9;i++)
{
if((mode & (0400>>i))==0)
{
p[i]='-';
continue;
}
p[i]=per[i%3];
}
}
int main(int argc, const char *argv[])
{
struct stat p;
struct tm *time_01=NULL;
char arr[10]="";
DIR *dp=opendir("../day2/");
if(NULL == dp)
{
perror("opendir");
return -1;
}
struct dirent *rp=NULL;
int count=1;
while(1)
{
rp=readdir(dp);
if(NULL==rp)
{
if(0==errno)
{
printf("读取完毕\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
if(rp->d_name[0]=='.')
continue;
char temp[100]={"../day2/"};
strcat(temp,rp->d_name);
if(stat(temp,&p)<0)
{
perror("stat");
return -1;
}
get_file(p.st_mode,arr);
printf("%s %ld ",arr,p.st_nlink);
time_01=localtime(&p.st_ctime);
printf("%d月 %02d %02d:%02d\t",time_01->tm_mon+1,time_01->tm_mday,time_01->tm_hour,time_01->tm_min);
printf("%s\n",rp->d_name);
}
closedir(dp);
return 0;
}
//结果展示
/*
linux@linux:~/Desktop/demo3/day4$ gcc 2.c
linux@linux:~/Desktop/demo3/day4$ ./a.out
rw-rw-r-- 1 4月 28 11:15 63
rw-rw-r-- 1 4月 28 14:32 ex.c
rw-rw-r-- 1 4月 29 14:45 six.c
rw-rw-r-- 1 4月 28 15:37 q.txt
rwxrwxr-x 2 4月 29 14:57 four
rw-rw-r-- 1 4月 29 10:15 two.c
rw-rw-r-- 1 4月 29 14:43 usr.txt
rwxrwxr-x 1 4月 29 14:42 a.out
rw-rw-r-- 1 4月 29 10:41 three.c
rw-rw-r-- 1 4月 28 11:15 1.c
rwxrwxr-x 2 4月 29 14:59 five
rw-rw-r-- 1 4月 28 14:48 2.c
rw-rw-r-- 1 4月 28 14:48 w.txt
rw-rw-r-- 1 4月 28 15:26 work2.c
rw-rw-r-- 1 4月 29 10:11 one.c
rw-rw-r-- 1 4月 29 14:31 work.c
读取完毕
linux@linux:~/Desktop/demo3/day4$ ls ../day2 -l
总用量 80
-rw-rw-r-- 1 linux linux 246 4月 28 11:15 1.c
-rw-rw-r-- 1 linux linux 312 4月 28 14:48 2.c
-rw-rw-r-- 1 linux linux 246 4月 28 11:15 63
*/