您的位置:首页 > 编程语言

编程实现 ls -l 命令所实现的功能

2013-09-22 20:25 169 查看


#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <grp.h>
#include <pwd.h>

char mode[10];/*声明一个存储权限的字符数组*/
void mode_info_my(mode_t st_mode,char *mode);/*函数声明*/

/*函数功能:按linux系统中ls -l命令格式,输出文件或者目录的信息*/
void my_stat(char *p)
{
char *time;
int t;
struct stat st_p;
if(stat(p,&st_p) == -1)
printf("stat error\n");
mode_info_my(st_p.st_mode,mode);
printf("%s",mode);
printf(" %ld",(long)st_p.st_nlink);
printf(" %s",getpwuid(st_p.st_uid)->pw_name);
printf(" %s",getgrgid(st_p.st_gid)->gr_name);
printf(" %ld",(long)st_p.st_size);
time=ctime(&st_p.st_ctime);
t=strlen(time);
time[t-1]='\0';
printf(" %s",time);
}

/*函数功能:获取文件或者目录的权限信息*/
void mode_info_my(mode_t st_mode,char *mode)
{

if(S_ISREG(st_mode))
mode[0]='-';
if(S_ISDIR(st_mode))
mode[0]='d';
if(S_ISCHR(st_mode))
mode[0]='c';
if(S_ISBLK(st_mode))
mode[0]='b';

if(st_mode & S_IRUSR)
mode[1]='r';
else
mode[1]='-';

if(st_mode & S_IWUSR)
mode[2]='w';
else
mode[2]='-';
if(st_mode & S_IXUSR)
mode[3]='x';
else
mode[3]='-';

if(st_mode & S_IRGRP)
mode[4]='r';
else
mode[4]='-';
if(st_mode & S_IWGRP)
mode[5]='w';
else
mode[5]='-';
if(st_mode & S_IXGRP)
mode[6]='x';
else
mode[6]='-';

if(st_mode & S_IROTH)
mode[7]='r';
else
mode[7]='-';
if(st_mode & S_IWOTH)
mode[8]='w';
else
mode[8]='-';
if(st_mode & S_IXOTH)
mode[9]='x';
else
mode[9]='-';
}

/*主函数*/
int main(int argc,char *argv[])
{

struct stat st;
struct dirent *dp;
DIR *c;
char p[256];
char *dir=NULL;
if(argc == 1){	/*命令行只有一个参数情况,默认显示当前路径信息*/
argv[1]=".";
}
if(argc>2){
printf("command error\n");
return 1;
}
if(stat(argv[1],&st) != 0){
printf("fail to get stat of file\n");
return -1;
}

mode_info_my(st.st_mode,mode);

if(mode[0] == 'd'){	/*路径为目录的相应操作*/
if((c=opendir(argv[1]))==NULL){		/*判断路径是否存在*/
printf("path is empty\n");
return -1;
}
if(chdir(argv[1])!=-1){		/*切换到所给路径*/
dir=getcwd(dir,0);
}
my_stat(dir);	/*输出目录信息*/
while((dp=readdir(c)) != NULL){		/*遍历目录下的文件和目录,并输出其信息*/
strcpy(p,argv[1]);
strcat(p,"/");
strcat(p,dp->d_name);	/*文件路径连接*/
my_stat(p);	/*打印信息*/
printf(" %s\n",dp->d_name);/*输出文件名*/
}
}

else	/*参数是文件,输出文件信息*/
my_stat(argv[1]);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ls_l.c