Linux系统编程使用函数仿写ls-l 的命令

1.题目

通过函数仿写ls-l的命令

包括 文件的大小,文件的创建时间,文件的权限,文件的名字,文件的类型

2.代码运行

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
void find_name(char *filename);
char get_file_r(char *filename);
char get_file_w(char *filename);
char get_file_x(char *filename);
char get_file_mode(struct stat buf);
#if 0
复写ls -l 命令  文件的大小,文件的创建时间,文件的权限,文件的名字,文件的类型
#endif
char name[4]={0};//保存  -rwx
char tim[6]={0};//保存年月日时分妙
int main(int argc,char *argv[])
{
	if(argc == 1)
		find_name(".");
	else
		find_name(argv[1]);
		return 0;
}
void find_name(char *filename)
{
	struct dirent *p=NULL;
	struct stat buf;
	struct tm * q =NULL;
	DIR *dir =opendir(filename);
	if(dir == NULL)
	{
		perror("opendir");
		return ;
	}
	while((p=readdir(dir))!=NULL)
	{
		if(strcmp(p->d_name,".")==0||strcmp(p->d_name,"..")==0)
		{
			continue;
		}
		else
		{
			lstat(p->d_name,&buf);
			name[0]=get_file_mode(buf);
			name[1]=get_file_r(p->d_name);
			name[2]=get_file_w(p->d_name);
			name[3]=get_file_x(p->d_name);
			q = localtime(&buf.st_ctime);
                tim[0]=q->tm_year+1900;
                tim[1]=q->tm_mon+1;
                tim[2]=q->tm_mday;
                tim[3]=q->tm_hour;
                tim[4]=q->tm_min;
                tim[5]=q->tm_sec;
                printf("%s %ld %d-%d-%d %d:%d:%d %s\n",name,buf.st_size,tim[0],tim[1],
                tim[2],tim[3],tim[4],tim[5],p->d_name);
		}
	}
}
char get_file_mode(struct stat buf)
{
	if(S_ISLNK(buf.st_mode))//判断文件类型
	{
		return 'l'; 
	}
	if(S_ISREG(buf.st_mode))
	{
		return '-';
	}
	if(S_ISDIR(buf.st_mode))
	{
		return 'd';
	}
	if(S_ISCHR(buf.st_mode))
	{
		return 'c';
	}
	if(S_ISBLK(buf.st_mode))
	{
		return 'b';
	}
	if(S_ISSOCK(buf.st_mode))
	{
		return 's';
	}
}
char get_file_r(char *filename)
{
	int n=access(filename,R_OK);//判断文件有没有读权限
	if(n == 0)
	{
		return 'r';
	}else{
		return '-';
	}
}
char get_file_w(char *filename)
{
	int n=access(filename,W_OK);//判断文件有没有写权限
	if(n == 0)
	{
		return 'w';
	}else{
		return '-';
	}
}
char get_file_x(char *filename)
{
	int n=access(filename,X_OK);//判断文件有没有执行权限
	if(n == 0)
	{
		return 'x';
	}else{
		return '-';
	}
}

3.运行结果

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值