1.终端输入:vim myls.c
2.编写代码:
#include <grp.h>
#include <pwd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <strings.h>
#include <sys/stat.h>
char *type_perm(mode_t mode);
int main(int argc,char **argv)
{
if(argc>2){
perror("输入错误\n");
exit(0);
}
struct stat info;
bzero(&info,sizeof(info));
stat(argv[1],&info);
//获取用户名的结构体与定义
struct passwd *my_info;
my_info=getpwuid(getuid());
//获取用户组名的结构体与定义
struct group *my_gid;
my_gid=getgrgid(getgid());
//char *wday[]={"Sun","Mon","tue","wed","Thu","Fri","Sat"};
char *wmon[]={"Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"};
if(S_ISDIR(info.st_mode)){
//打开目录:获取目录的访问入口
DIR *dp=opendir(argv[1]);
chdir(argv[1]);
if(dp==NULL){
printf("打开目录[%s]失败\n",argv[1]);
exit(0);
}
//不断地读取目录项
struct dirent *ep;
while(1){
ep=readdir(dp);//读取目录,得到目录指针
if(ep==NULL)//读完了全部目录项
break;
if(ep->d_name[0]=='.')//跳过隐藏文件
continue;
bzero(&info,sizeof(info));
stat(ep->d_name,&info);
//获取时间的结构体与定义
time_t timep;
struct tm *p;
ctime(&info.st_mtim.tv_sec);
p=localtime(&info.st_mtim.tv_sec);
printf("%s ",type_perm(info.st_mode));//输出文件类型和权限
printf("%ld ",info.st_nlink);//输出链向此文件的连接数(硬连接)
printf("%s ",my_info->pw_name);//输出文件的所有者
printf("%s ",my_gid->gr_name);//输出文件的所在组
printf("%8ld ",info.st_size);//定间隔输出文件的大小
printf("%s %2d %2d:%2d ",wmon[p->tm_mon],p->tm_mday,p->tm_hour,p->tm_min);//定间隔输出文件最近的修改时间
printf("%s\n",ep->d_name);//输出名字
}
closedir(dp);
}
else{
//获取时间的结构体与定义
time_t timep;
struct tm *p;
ctime(&info.st_mtim.tv_sec);
p = localtime(&info.st_mtim.tv_sec);
//输出文件类型和权限
printf("%s ", type_perm(info.st_mode));
// 输出链向此文件的连接数(硬连接)
printf("%ld ",info.st_nlink);
// 输出文件的所有者
printf("%s ",my_info->pw_name);
// 输出文件的所在组
printf("%s ",my_gid->gr_name);
// 定间隔输出文件的大小
printf("%4ld ", info.st_size);
// 定间隔输出文件的最近修改时间
printf("%s %2d %2d:%2d ", wmon[p->tm_mon], p->tm_mday, p->tm_hour, p->tm_min);
// 输出名字
printf("%s\n", argv[1]);
}
return 0;
}
char *type_perm(mode_t mode)
{
static char result[11];
switch(mode & S_IFMT)
{
case S_IFBLK: result[0] = 'b'; break;
case S_IFCHR: result[0] = 'c'; break;
case S_IFREG: result[0] = '-'; break;
case S_IFIFO: result[0] = 'p'; break;
case S_IFSOCK:result[0] = 's'; break;
case S_IFLNK: result[0] = 'l'; break;
case S_IFDIR: result[0] = 'd'; break;
}
char rwx[] = {'r', 'w', 'x'};
for(int i=0; i<9; i++)
{
result[i+1] = mode&(0400>>i) ? rwx[i%3] : '-';
}
return result;
}
3.编译:gcc myls.c -o myls
4.运行:./myls .
或者./myls 目录(比如:./myls /etc)