【二十六】 Linux网络编程——模仿linux的ls命令实现

【二十六】      Linux网络编程——模仿linux的ls命令实现

/*my_ls.c*/

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


int display_file(char *argv,char *fname)
{   
	struct stat buf;
	struct tm *tp;

	if (lstat(argv, &buf) < 0)
	{
		perror("fail to lstat");
		return -1;
	}

	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;
	}

	int n;

	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");
			}
		}
		else
		{
			printf("-");
		}
	}

	printf("%2d", buf.st_nlink);
	printf(" %s", getpwuid(buf.st_uid)->pw_name);
	printf(" %s", getgrgid(buf.st_gid)->gr_name);
	printf(" %8ld", buf.st_size);
	tp = localtime(&buf.st_mtime);
	printf(" %4d-%d-%d %2d:%2d", tp->tm_year+1900, tp->tm_mon+1, tp->tm_mday, tp->tm_hour, tp->tm_min);
	printf(" %s\n", fname);

	return 0;
}

int main(int argc,char *argv[])
{    
	struct stat buf;
    DIR *mydir;
    struct dirent *dirp;
    char path[256];

	if (argc < 2)
	{
		printf("Usage : %s <file>\n", argv[0]);
		return -1;
	}

    if(lstat(argv[1],&buf)<0)
    {
        perror("fail to lstat");
        return -1;
    }

    if((buf.st_mode & S_IFMT)==S_IFDIR)
	{
        mydir=opendir(argv[1]);
        while((dirp=readdir(mydir))!=NULL)
        {   
            if(dirp->d_name[0]=='.') continue;
            sprintf(path,"%s/%s",argv[1],dirp->d_name);
            display_file(path,dirp->d_name);
        }
    }
    else
    {
        display_file(argv[1],argv[1]);
    }

    return 0;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值