Linux---Ls命令 初级实现

时间:2024-03-30 18:07:43

By xxx0624
Done:
    ls
    ls -a
    ls -l
    ls /tmp
    ls -R
    ls -t
    FileName color
    FileName output

 /*
By xxx0624
Done:
ls
ls -a
ls -l
ls /tmp
ls -R
ls -t
FileName color
FileName output
*/ #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/ioctl.h>
#include<dirent.h>
#include<pwd.h>
#include<grp.h>
#include<unistd.h>
/*head file*/ #define LenOfName 256
#define maxN 1005
#define maxM 505
#define maxL 105
#define LenOfPath 256<<4
#define LS 0 //ls
#define LS_A 1 //ls -a
#define LS_L 2 //ls -l
#define LS_TMP 3 //ls /tmp
#define LS_R 4 //ls -R
#define LS_T 5 //ls -t
/*define file*/ void do_ls( int,char [] );
void dostat( char * );
void show_file_info( char *,struct stat * );
void mode_to_letters( int,char [] );
char *uid_to_name( uid_t );
char *gid_to_name( gid_t );
void getcolor( char * );
int get_file_type( char * );
int get_modify_time( char * );
void getWidth();
void display_R( char * );
int cmp1( const void * ,const void * );
int cmp2( const void * ,const void * );
int cmp3( const void * ,const void * ); struct outputFile{
char FileName[ LenOfName ];
int modify_time ;
int file_type ;
}Output[ maxN ],OutputPoint[ maxM ],Temp[ maxN+maxM ];
int colormode,foreground,background;
int terminalWidth ; void dostat( char *filename ){
struct stat info;
if( stat( filename,&info )==- ){
perror( filename );
}
else{
getcolor( filename );
show_file_info( filename,&info );
}
return ;
}
/*get file info*/ void mode_to_letters( int mode,char str[] ){
strcpy( str,"----------" ); if( S_ISDIR( mode ) ) str[] = 'd';
if( S_ISCHR( mode ) ) str[] = 'c';
if( S_ISBLK( mode ) ) str[] = 'b'; if( mode&S_IRUSR ) str[] = 'r';
if( mode&S_IWUSR ) str[] = 'w';
if( mode&S_IXUSR ) str[] = 'x'; if( mode&S_IRGRP ) str[] = 'r';
if( mode&S_IWGRP ) str[] = 'w';
if( mode&S_IXGRP ) str[] = 'x'; if( mode&S_IROTH ) str[] = 'r';
if( mode&S_IWOTH ) str[] = 'w';
if( mode&S_IXOTH ) str[] = 'x'; return ;
} char *uid_to_name( uid_t uid ){
struct passwd *pw_ptr;
static char numstr[ ];
if( (pw_ptr = getpwuid( uid ) )==NULL ){
sprintf(numstr,"%d",uid);
return numstr;
}
else{
return pw_ptr->pw_name;
}
}
char *gid_to_name( gid_t gid ){
struct group *grp_ptr;
static char numstr[ ];
if( (grp_ptr = getgrgid( gid ) )==NULL ){
sprintf(numstr,"%d",gid);
return numstr;
}
else{
return grp_ptr->gr_name;
}
}
/*get userid & groupid*/ int get_file_type( char *filename ){
struct stat info;
stat( filename,&info );
int file_type = ;
file_type = info.st_mode & S_IFMT;
return file_type;
}
/*get file type*/ int get_modify_time( char *filename ){
struct stat info;
stat( filename,&info );
int modify_time = ;
modify_time = info.st_mtime;
return modify_time;
}
/*get file last modify time*/ int isadir(char *str)
{
struct stat info; return ( lstat(str,&info) != - && S_ISDIR(info.st_mode) );
}
/*judge the file is or not a dir*/ void display_R( char *filename ){
char fullpath[ LenOfPath ];
struct outputFile Output2[ maxN ];
getcolor( filename );
printf("\033[%d;%d;%dm%s\033[0m :\n",colormode,foreground,background,filename);
DIR * dir_ptr ;
struct dirent *direntp;
int cntTemp = ;
int i ;
if( (dir_ptr = opendir( filename ) )==NULL ){
fprintf( stderr,"myls:cannot open %s\n",filename );
closedir( dir_ptr );
return ;
}
else {
while( (direntp = readdir( dir_ptr ))!=NULL ){
if( strcmp( direntp->d_name,"." )==||strcmp( direntp->d_name,".." )== )
continue;
strcpy( Output2[ cntTemp ].FileName,direntp->d_name );
strcpy( Output[ cntTemp ].FileName,direntp->d_name );
cntTemp ++ ;
}
closedir( dir_ptr );
if( cntTemp> ){
qsort( Output2,cntTemp,sizeof( Output2[] ),cmp1 );
qsort( Output,cntTemp,sizeof( Output[] ),cmp1 );
}
display_Ls( cntTemp );
for( i=;i<cntTemp;i++ ){
memset( fullpath,'\0',sizeof( fullpath ) );
strcpy( fullpath,filename );
strcat( fullpath,"/" );
strcat( fullpath,Output2[ i ].FileName );
if( isadir( fullpath ) )
display_R( fullpath );
}
}
return ;
}
/*active ls -R && Output */ void getWidth(){
char *tp;
struct winsize wbuf;
terminalWidth = ;
if( isatty(STDOUT_FILENO) ){
if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &wbuf) == - || wbuf.ws_col == ){
if( tp = getenv("COLUMNS") )
terminalWidth = atoi( tp );
}
else
terminalWidth = wbuf.ws_col;
}
return ;
}
/******************************************************************
得出终端的宽度,默认宽度为80,如果获取失败,将激活-1选项
*******************************************************************/ int cmp1( const void *p ,const void *q ){
char T1[ LenOfName ],T2[ LenOfName ];
strcpy( T1,(*(struct outputFile *)p).FileName );
strcpy( T2,(*(struct outputFile *)q).FileName );
int len1 = strlen( T1 );
int i ;
for( i=;i<len1;i++ ){
if( T1[ i ]>='A' && T1[ i ]<='Z' ){
T1[ i ] = T1[ i ] - 'A' + 'a';
}
}
int len2 = strlen( T2 );
for( i=;i<len2;i++ ){
if( T2[ i ]>='A' && T2[ i ]<='Z' ){
T2[ i ] = T2[ i ] - 'A' + 'a';
}
}
return strcmp( T1,T2 );
}
/********************************************************
文件名排序 cmp1
*********************************************************/ int cmp2( const void *p,const void *q ){
return (*(struct outputFile *)p).file_type < (*(struct outputFile *)q).file_type ;
}
/********************************************************
文件类型排序 cmp2
*********************************************************/ int cmp3( const void *p,const void *q ){
return (*(struct outputFile *)p).modify_time < (*(struct outputFile *)q).modify_time ;
}
/********************************************************
文件修改时间排序 cmp3
*********************************************************/ void show_file_info( char *filename,struct stat * info_p ){
char modestr[ ]; mode_to_letters( info_p->st_mode,modestr ); printf("%s",modestr);
printf("%4d ",(int)info_p->st_nlink);
printf("%-8s ",uid_to_name(info_p->st_uid));
printf("%-8s ",gid_to_name(info_p->st_gid));
printf("%8ld ",(long)info_p->st_size);
printf("%.12s ",+ctime(&info_p->st_mtime));
printf("\033[%d;%d;%dm%s\033[0m\n",colormode,foreground,background,filename);
return ;
}
/*******************************************************
ls -l 的输出
********************************************************/ void getcolor( char *filename ){
struct stat info;
stat( filename,&info );
foreground = ;
background = ;
colormode = ;
switch ( (info.st_mode & S_IFMT) ){
case S_IFREG: /*regular 普通文件 , 白色*/
foreground = ;
break;
case S_IFLNK: /*symbolic link 链接文件 , 青蓝色*/
foreground = ;
colormode = ;
break;
case S_IFSOCK: /*紫红色*/
foreground = ;
colormode = ;
break;
case S_IFDIR: /*directory 目录文件 , 蓝色*/
foreground = ;
break;
case S_IFBLK: /*block special 块设备文件 , 黄色*/
foreground = ;
colormode = ;
break;
case S_IFCHR: /*character special 字符设备文件 , 黄色*/
foreground = ;
colormode = ;
break;
case S_IFIFO: /*fifo 绿色*/
foreground = ;
colormode = ;
break;
}
}
/*******************************************************
给文件添加颜色
********************************************************/ void display_Ls( int cnt ){
int wordLenMax = ;//the LenMax word
int wordRowNum = ;//the amount of one row
int wordColNum = ;//the amount of one col
int i , j;
for( i=;i<cnt;i++ ){
if( i== ) wordLenMax = strlen( Output[ i ].FileName );
else wordLenMax = wordLenMax>strlen( Output[ i ].FileName )?wordLenMax:strlen( Output[ i ].FileName );
}
wordLenMax += ;
wordRowNum = terminalWidth / wordLenMax;
if( cnt%wordRowNum== ) wordColNum = cnt / wordRowNum;
else wordColNum = cnt / wordRowNum + ;
for( i=;i<wordColNum;i++ ){
j = i;
while( j<cnt ){
getcolor( Output[ j ].FileName );
printf("\033[%d;%d;%dm%-15s\033[0m ",colormode,foreground,background,Output[ j ].FileName);
j += wordColNum;
}
printf("\n");
}
return ;
}
/**********************************************************
ls的分栏输出
***********************************************************/ void display_Ls_a( int cntPoint,int cnt ){
int CNT = ;
int wordLenMax = ;//the LenMax word
int wordRowNum = ;//the amount of one row
int wordColNum = ;//the amount of one col
int i , j;
for( i=;i<cntPoint;i++ ){
strcpy( Temp[ CNT ].FileName,OutputPoint[ i ].FileName );
Temp[ CNT ].file_type = OutputPoint[ i ].file_type;
Temp[ CNT ].modify_time = OutputPoint[ i ].modify_time;
CNT ++;
wordLenMax = wordLenMax>strlen( OutputPoint[ i ].FileName )?wordLenMax:strlen( OutputPoint[ i ].FileName );
}
for( i=;i<cnt;i++ ){
strcpy( Temp[ CNT ].FileName,Output[ i ].FileName );
Temp[ CNT ].file_type = Output[ i ].file_type;
Temp[ CNT ].modify_time = Output[ i ].modify_time;
CNT ++;
wordLenMax = wordLenMax>strlen( Output[ i ].FileName )?wordLenMax:strlen( Output[ i ].FileName );
}
wordLenMax += ;
wordRowNum = terminalWidth / wordLenMax;
if( CNT%wordRowNum== ) wordColNum = CNT / wordRowNum;
else wordColNum = CNT / wordRowNum + ;
for( i=;i<wordColNum;i++ ){
j = i;
while( j<CNT ){
getcolor( Temp[ j ].FileName );
printf("\033[%d;%d;%dm%-15s\033[0m ",colormode,foreground,background,Temp[ j ].FileName);
j += wordColNum;
}
printf("\n");
}
return ;
}
/**********************************************************
ls -a 的分栏输出
***********************************************************/ void display_Ls_tmp( int cnt ){
display_Ls( cnt );
return ;
}
/**********************************************************
ls /tmp 的分栏输出
***********************************************************/ void display_Ls_R( char *filename ){
char fullpath[ LenOfPath ];
strcpy( fullpath,get_current_dir_name() );
strcat( fullpath,"/" );
strcat( fullpath,filename );
display_R( fullpath );
return ;
}
/**********************************************************
ls -R 的分栏输出
***********************************************************/ void do_ls( int myJudge,char myOrder[] ){
if( myJudge==LS_R ){
display_Ls_R( "." );
return ;
}
/**********************************************************
ls -R
***********************************************************/
char dirname[ maxL ];
if( myJudge!=LS_TMP ){
strcpy( dirname,"." );
}
else {
strcpy( dirname,myOrder );
}
DIR * dir_ptr;
struct dirent *direntp;
int cntOutput = ;
int cntOutputPoint = ;
if( ( dir_ptr = opendir( dirname ) )==NULL ){
fprintf( stderr,"myls:cannot open %s\n",dirname );
}
else{
while( (direntp = readdir( dir_ptr ) )!=NULL ){
if( direntp->d_name[ ]=='.' ) {
strcpy( OutputPoint[ cntOutputPoint ].FileName,direntp->d_name );
OutputPoint[ cntOutputPoint ].file_type = get_file_type( OutputPoint[ cntOutputPoint ].FileName );
OutputPoint[ cntOutputPoint ].modify_time = get_modify_time( OutputPoint[ cntOutputPoint ].FileName );
cntOutputPoint ++;
}
else {
strcpy( Output[ cntOutput ].FileName,direntp->d_name );
Output[ cntOutput ].file_type = get_file_type( Output[ cntOutput ].FileName );
Output[ cntOutput ].modify_time = get_modify_time( Output[ cntOutput ].FileName );
cntOutput ++;
}
} if( myJudge==LS_T ){
qsort( OutputPoint,cntOutputPoint,sizeof( OutputPoint[] ),cmp3 );
qsort( Output,cntOutput,sizeof( Output[] ),cmp3 );
}
else {
qsort( OutputPoint,cntOutputPoint,sizeof( OutputPoint[] ),cmp1 );
qsort( Output,cntOutput,sizeof( Output[] ),cmp1 );
}
/**********************************************************
预处理输出
***********************************************************/
if( myJudge==LS||myJudge==LS_T ){
display_Ls( cntOutput );
closedir( dir_ptr );
}
/**********************************************************
ls && ls -t
***********************************************************/
else if( myJudge==LS_A ){
display_Ls_a( cntOutputPoint,cntOutput );
closedir( dir_ptr );
}
/**********************************************************
ls -a
***********************************************************/
else if( myJudge==LS_L ){
int i;
for( i=;i<cntOutput;i++ )
dostat( Output[ i ].FileName );
closedir( dir_ptr );
}
/**********************************************************
ls -l
***********************************************************/
else {
display_Ls_tmp( cntOutput );
closedir( dir_ptr );
}
/**********************************************************
ls /tmp
***********************************************************/
}
return ;
}/*sovle*/ int main( int argc, char *argv[] ){
getWidth( );
int i ;
if( argc== ){
do_ls( LS,"ls" );
}
else{
int ord;
while( (ord = getopt(argc,argv,":laRt"))!=- ){
switch( ord ){
case 'a':
do_ls( LS_A,"ls-a" );
break;
case 'l':
do_ls( LS_L,"ls-l" );
break;
case 'R':
do_ls( LS_R,"ls-R" );
break;
case 't':
do_ls( LS_T,"ls-t" );
break;
default :
break;
}
}
for( i=;i<argc;i++ ){
if( argv[ i ][ ]=='-' ) continue;
printf("%s:\n",argv[ i ]);
do_ls( LS_TMP,argv[ i ] );
}
}
return ;
}
/*main*/