需要掌握知识点有:
标准IO和系统IO,stat函数 ,目录路径
标准IO与系统IO学习:
stat函数 使用:
目录路径:
- mkdir():创建空目录
- opendir():打开指定目录,注意打开并不意味着进入
- readdir():读取指定目录,将获得的是目录项
- chdir():切换进程当前路径
- getcwd():获取进程当前路径
- closedir():关闭目录
目录的操作:
如果在使用目录的命令时,你对路径比较熟悉,那你的出错率就减低百分五十。
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <stdbool.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <dirent.h>
void show_mode(struct stat *buf);
void show_power(struct stat * buf);
int main(int argc,char** argv)
{
//判断argc是否为2
if(argc != 2)
{
printf("打开文件不符:%s<目标文件>\n",argv[0]);
}
//定义一个stat,把文件代入
struct stat info;
bzero(&info,sizeof(info));
stat(argv[1],&info);
//判断文件类型
if(!S_ISDIR(info.st_mode))
{
//打印文件类型
show_mode(&info);
//打印文件权限
show_power(&info);
//打印软连接数
printf("%lu ",info.st_nlink);
//打印所有者
printf("%s ",getpwuid(info.st_uid)->pw_name);
//打印所有组
printf("%s ",getgrgid(info.st_gid)->gr_name);
//打印大小
printf("%ld ",info.st_size);
//打印最近修改时间
printf("%s ",strtok(ctime(&info.st_mtim.tv_sec),"\n"));
//打印文件名字
printf("%s\n",argv[1]);
}
if(S_ISDIR(info.st_mode))
{
//打开目录文件
DIR* dp = opendir(argv[1]);
//判断是否能打开
if(dp == NULL)
{
perror("打开失败");
exit(0);
}
//进入目录当中
//并把当前路径保存下来
chdir(argv[1]);
char adr[100];
bzero(adr,100);
getcwd(adr,100);
//遍历读取目录当中的文件
struct dirent * ep;
while(1)
{
ep= readdir(dp);
if(ep == NULL)
{
printf("mission completed\n");
break;
}
//跳过为.或..文件
//
if(ep->d_name[0] == '.')
continue;
//获取文件的属性
struct stat buf;
bzero(&buf,sizeof(buf));
stat(ep->d_name,&buf);
//输出文件的的信息
//打印文件类型
show_mode(&buf);
//打印文件权限
show_power(&buf);
//打印软连接数
printf("%lu ",buf.st_nlink);
//打印所有者
printf("%s ",getpwuid(buf.st_uid)->pw_name);
//打印所有组
printf("%s ",getgrgid(buf.st_gid)->gr_name);
//打印大小
printf("%ld ",buf.st_size);
//打印最近修改时间
printf("%s ",strtok
(ctime(&buf.st_mtim.tv_sec),"\n"));
//打印文件名字
printf("%s\n",ep->d_name);
}
}
chdir(adr);
return 0;
}
void show_mode(struct stat *buf)
{
switch(buf->st_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;
case S_IFIFO: printf("p ");break;
}
}
void show_power(struct stat * buf)
{
char arr[3] = {'r','w','x'};
for(int i = 0;i<9;i++)
{
printf("%c",buf->st_mode & (0400>>i) ? arr[i%3] :'-');
}
printf(" ");
}