linux下c语言完成定制自己的ls命令(至少使用三种参数)
2018-07-06 20:23:45 q_2478857829 阅读数 352更多
分类专栏: linux入门
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_38146797/article/details/80945840
定制自己的ls命令,要求提供至少三种参数,对应三种不同的输出方式。
源码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <dirent.h>
int fun1(char *dir,char *filename,int lflag)
{
int n;
struct stat buf;
char out[100];
// struct passwd *pw;
// struct group *gr;
struct tm *t;
if (lflag==0)
{
printf("%s\t",filename);
return 0;
}
if(lstat(dir,&buf)<0)
{
fprintf(stderr,"stat error:%s\n",strerror(errno));
return -1;
}
switch(buf.st_mode & S_IFMT)
{
case S_IFLNK:
printf("l");
break;
case S_IFSOCK:
printf("s");
break;
}
for(n=8;n>=0;n--)
{
if(buf.st_mode&(1<<n))
{
switch(n%3)
{
case 2:
printf("r");
break;
case 1:
printf("w");
break;
case 0:
printf("x");
break;
default:
break;
}
}
else
{
printf("-");
}
}
printf(" %d",buf.st_nlink);
struct passwd *pw;
pw = getpwuid(buf.st_uid);
printf(" %s",pw->pw_name);
struct group *gr;
gr = getgrgid(buf.st_gid);
printf(" %s",gr->gr_name);
printf(" %ld",buf.st_size);
t = localtime(&buf.st_atime);
printf(" %d-%d-%d %d:%d",t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min);
printf(" %s ",filename);
if(S_ISLNK(buf.st_mode))
{
printf(" -> ");
if(readlink(filename,out,100)==-1)
{
}
printf("%s",out);
}
printf("\n");
return 0;
}
int ls_prepare(char *w,int aflag,int lflag){
struct stat buf;
char name[100];
DIR *dir;
struct dirent *pdr;
if(lstat(w,&buf)<0)
{
fprintf(stderr,"stat error:%s\n",strerror(errno));
return -1;
}
if(S_ISDIR(buf.st_mode))
{
DIR *dir;
dir = opendir(w);
struct dirent *pdr;
while ((pdr = readdir(dir))!=NULL)
{
if(aflag==0)
{
if(pdr->d_name[0]=='.')
continue;
memset(name,0,100);
strcpy(name,w);
strcat(name,"/");
strcat(name,pdr->d_name);
fun1(name,pdr->d_name,lflag);
}else
{
memset(name,0,100);
strcpy(name,w);
strcat(name,"/");
strcat(name,pdr->d_name);
fun1(name,pdr->d_name,lflag);
}
}
closedir(dir);
}
else
{
fun1(w,w,lflag);
}
return 0;
}
int main(int argc ,char **argv)
{
int aflag=0;
int lflag=0;
char c;
int i;
while((c=getopt(argc,argv,"al"))!=-1)
{
switch(c)
{
case 'a':aflag=1;break;
case 'l':lflag=1;break;
default:break;
}
}
if (argc==optind)
{
ls_prepare("./",aflag,lflag);
}
else
{
for(i=optind;i<argc;i++)
ls_prepare(argv[i],aflag,lflag);
}
printf("\n");
return 0;
}
欢迎留言!