1.1. 打印指定目录下的所有文件名,除了隐藏文件,输入编号,可以将编号对应的文件内容显示在终端上。
2.2. 显示指定路径下所有文件的权限 硬链接数 时间 以及名字
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>
#include<time.h>
#include<errno.h>
char *filemode(mode_t mode)
{
static char getper[10]="";
char per[]="rwx";
for(int i=0;i<9;i++)
{
if((mode&(0400>>i))==0)
{
getper[i]='-';
continue;
}
getper[i] = per[i%3];
}
return getper;
}
void filepression(const char *pathname)
{
struct stat buf;
if(stat(pathname,&buf)<0)
{
perror("stat");
return;
}
filemode(buf.st_mode);
printf("%s",filemode(buf.st_mode));
//硬链接数
printf(" %ld",buf.st_nlink);
//文件所属用户,以及组用户名
printf(" %d %d",buf.st_uid,buf.st_gid);
//文件大小
printf(" %ld",buf.st_size);
//时间
struct tm time;
localtime_r(&buf.st_mtime,&time);
printf(" %d.%02d.%02d %02d:%02d:%02d",time.tm_year+1900,time.tm_mon+1,time.tm_mday,time.tm_hour,time.tm_min,time.tm_sec);
//文件名
printf(" %s\n",pathname);
}
int main(int argc, const char *argv[])
{
DIR *dp = opendir("../day3/");
if(NULL==dp)
{
perror("opendir");
return -1;
}
struct dirent * rp =NULL;
while(1)
{
rp =readdir(dp);
if(NULL == rp)
{
if(0==errno)
{
printf("目录文件读取完毕\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
filepression(rp->d_name);
}
return 0;
}
结果:
rw-rw-r-- 1 1000 1000 1333 2023.05.04 22:40:08 zy2.c
rw-rw-r-- 1 1000 1000 844 2023.05.04 17:11:36 07_stat.c
rw-rw-r-- 1 1000 1000 946 2023.05.04 20:15:34 cs.c
rwxrwxr-- 1 1000 1000 12 2023.05.04 19:47:55 open.txt
rwxrwxr-x 5 1000 1000 4096 2023.05.04 10:21:01 ..
rwxrwxr-x 2 1000 1000 4096 2023.05.04 22:43:27 .
rwxrwxr-x 1 1000 1000 12936 2023.05.04 22:43:27 a.out
rw-rw-r-- 1 1000 1000 396 2023.05.04 11:10:57 02_open.c
rw-rw-r-- 1 1000 1000 1069 2023.05.04 22:32:46 06_dir.c
rw-rw-r-- 1 1000 1000 7 2023.05.04 13:58:33 read.txt
rwxrwxrwx 1 1000 1000 396 2023.05.04 20:15:38 copy.txt
rw-rw-r-- 1 1000 1000 1 2023.05.04 21:42:20 05_huanchong.c
rw-rw-r-- 1 1000 1000 456 2023.05.04 20:42:27 04_read.c