1. 打印指定目录下的所有文件名,除了隐藏文件,输入编号,可以将编号对应的文件内容显示在终端上。
//代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
//1.指针数组
int main(int argc, const char *argv[])
{
DIR *dp = opendir("../day3/"); //目录流指针
if(NULL == dp)
{
perror("opendir");
return -1;
}
int count=1,i=0;
struct dirent *rdp[99];
while(1)
{
struct dirent *rp = readdir(dp);
if(NULL == rp)
{
if(0 == errno)
{
printf("目录输出完毕\n"); //返回NULL并且不更新errno时,输出完毕
break;
}
else
{
perror("readdir");
return -1;
}
}
if(rp->d_name[0] != '.')
{
printf("[%d] %s\n",count++,rp->d_name);
rdp[i++] = rp;
}
}
int n;
printf("请输入查看文件编号:");
scanf("%d",&n);
int fd = open(rdp[n-1]->d_name, O_RDONLY);
if(fd == -1)
{
perror("open");
return -1;
}
char buf[32] = "";
while(1)
{
bzero(buf,sizeof(buf));
int res = read(fd,buf,sizeof(buf)-1);
if(res == 0)
break;
printf("%s",buf);
}
close(fd);
closedir(dp);
return 0;
}
2. 显示指定路径下所有文件的权限 硬链接数 时间 以及名字
//代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include <dirent.h>
void get_FilePermission(mode_t mode)
{
for(int i=0,t=0400;i<9;i++,t=t>>1)
{
if((mode&t) && i%3==0)
putchar('r');
else if((mode&t) && i%3==1)
putchar('w');
else if((mode&t) && i%3==2)
putchar('x');
else
putchar('-');
}
}
void FileInfo(const char *pathname)
{
struct stat buf;
if(stat(pathname,&buf) < 0)
{
perror("stat");
return;
}
//文件类型和权限
get_FilePermission(buf.st_mode);
//硬链接数
printf(" %ld",buf.st_nlink);
//用户和用户组
printf(" %d %d",buf.st_uid,buf.st_gid);
//文件大小
printf(" %5ld",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;
}
while(1)
{
struct dirent *rp = readdir(dp);
if(NULL == rp)
{
if(0 == errno)
break;
else
return -1;
}
FileInfo(rp->d_name);
}
closedir(dp);
return 0;
}
//运行结果
zzy@zzy-vm:~/hqyj/IO/day3$ ./a.out
rw-rw-r-- 1 1000 1000 694 2023.05.04 18:26:06 test1.c
rwxrwxr-x 1 1000 1000 663 2023.05.04 13:39:43 copy.txt
rw-rw-r-- 1 1000 1000 1267 2023.05.04 18:42:10 test3.c
rwxrwxr-x 7 1000 1000 4096 2023.05.04 10:10:08 ..
rw-rw-r-- 1 1000 1000 1065 2023.05.04 17:22:24 test5.c
rwxrwxr-x 2 1000 1000 4096 2023.05.04 18:42:14 .
rwxrwxr-x 1 1000 1000 17256 2023.05.04 18:42:14 a.out
rw-rw-r-- 1 1000 1000 1087 2023.05.04 18:28:17 test4.c
rw-rw-r-- 1 1000 1000 1065 2023.05.04 17:22:07 test2.c