UC高级编程--实现myls程序

跟着达内视频,学习UC高级编程,完毕程序小练习。

主要练习的函数为:

 int lstat(const char *path, struct stat *buf);

 size_t strftime(char *s, size_t max, const char *format,  const struct tm *tm);此函数, 第一次使用。

time_t mktime(struct tm *tm);//把分离的时间合成整数,写项目代码中,当时自己实现了这个函数功能。

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

void show01(struct stat st)//文件属性-rwxr--r--
{	
	/*打印文件类型*/
    if (S_ISLNK(st.st_mode)) {
        printf("l");
    } else if (S_ISREG(st.st_mode)) {
        printf("-");
    } else if (S_ISDIR(st.st_mode)) {
        printf("d");
    } else if (S_ISCHR(st.st_mode)) {
        printf("c");
    } else if (S_ISBLK(st.st_mode)) {
        printf("b");
    } else if (S_ISFIFO(st.st_mode)) {
        printf("f");
    } else if (S_ISSOCK(st.st_mode)) {
        printf("s");
    }	
	/*U文件全部者的权限*/
    if (st.st_mode & S_IRUSR){
        printf("r");
    } else {
        printf("-");
    }
    if (st.st_mode & S_IWUSR){
        printf("w");
    } else {
        printf("-");
    }
    if (st.st_mode & S_IXUSR){
        printf("x");
    } else {
        printf("-");
    }
	/*G文件全部组的权限*/
    if (st.st_mode & S_IRGRP){
        printf("r");
    } else {
        printf("-");
    }
    if (st.st_mode & S_IWGRP){
        printf("w");
    } else {
        printf("-");
    }
    if (st.st_mode & S_IXGRP){
        printf("x");
    } else {
        printf("-");
    }
	/*O其他用户的权限*/
    if (st.st_mode & S_IROTH){
        printf("r");
    } else {
        printf("-");
    }
    if (st.st_mode & S_IWOTH){
        printf("w");
    } else {
        printf("-");
    }
    if (st.st_mode & S_IXOTH){
        printf("x");
    } else {
        printf("-");
    }
	printf(" ");
}

void show02(struct stat st)//硬链接数
{
	printf("%lu", st.st_nlink);
	printf(" ");
}

void show03(struct stat st)//username
{
	struct passwd *psd ;
	psd = getpwuid(st.st_uid);
    printf("%s", psd->pw_name);
	printf(" ");
}

void show04(struct stat st)//组名
{
	struct group *grp = getgrgid(st.st_gid);
	printf("%s", grp->gr_name);
	printf(" ");	
}

void show05(struct stat st)//文件大小
{
	printf("%lu", st.st_size);
	printf(" ");	
}

void show06(struct stat st)//文件时间
{
	char timebuf[20];
	struct tm* newtime = localtime(&st.st_mtime);
	strftime(timebuf, 20,"%B %d %H:%M",newtime);
	printf("%s", timebuf);                
	printf(" ");	
}

void show07(const char *fname)//文件名
{
	printf("%s", fname);                
	printf(" ");
}

int main(int argc, const char *argv[])
{
	int ret = 0;
	struct stat st;
	
	if(argc<2)
	{
		printf("./a.out file
");return ;
	}
	ret = lstat(argv[1], &st);
	if(ret<0) perror("lstat()");

	show01(st);	
	show02(st);
	show03(st);
	show04(st);
	show05(st);
	show06(st);
	show07(argv[1]);
	
	puts("");//换行
	return 0;
}

函数的接口设计的方面,不是非常合理,主要是练习函数的使用。 


原文地址:https://www.cnblogs.com/hrhguanli/p/4007246.html