2023.09.07

#include 
char *get_power_file(mode_t m);
int main(int argc, const char *argv[])
{
	DIR* dp=opendir(argv[1]);
    //合法性判断
	if(NULL==dp){
		perror("opendir");
		return -1;
	}
	struct dirent *rp=NULL;
	while(1){
		rp=readdir(dp);
		if(NULL==rp){
			break;}
		if('.'!=rp->d_name[0]){
		//文件
	    char place[100]="";
        //保存路径
	    strcpy(place,argv[1]);
        //判断路径最后是否有‘/’
    	if(place[strlen(argv[1])-1]!='/'){
		    place[strlen(argv[1])]='/';
	    }
        //拼接出完整路径
		strcat(place,rp->d_name);
		struct stat buf;
        //合法性判断
		if(stat(place,&buf)<0){
			perror("stat");
			return -1;
		}
		//文件类型及权限
		char *p=get_power_file(buf.st_mode);
		printf("%s",p);
		//文件硬连接数
		int res=buf.st_nlink;
		printf(" %d",res);
		//uid
		struct passwd* pwd=getpwuid(buf.st_uid);
		if(NULL==pwd){
			perror("getpwuid");
			return -1;
		}
		printf(" %s",pwd->pw_name);
		//gid
		struct group* grp=getgrgid(buf.st_gid);
		if(NULL==grp){
			perror("getgrgid");
			return -1;
		}
		printf(" %s",grp->gr_name);
		//文件大小
		int size=buf.st_size;
		printf(" %d",size);
		//文件时间戳
		struct tm* info = NULL;
		info=localtime(&buf.st_atime);
		printf(" %d年-%02d月-%02d日 %02d:%02d:%02d",info->tm_year+1900,info->tm_mon+1,\
                            info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
		printf(" %s",rp->d_name);
		putchar(10);
		}
	}
	closedir(dp);
	return 0;
}
//获取文件类型及权限的函数
char *get_power_file(mode_t m)
{
	char a[4]="rwx";
	static char p[11]="";
	char* d=p;
	 switch (m & S_IFMT) {
	 	case S_IFBLK: break;
        case S_IFCHR: strcpy(p,"b");break;
        case S_IFDIR: strcpy(p,"c");break;
		case S_IFIFO: strcpy(p,"p");break;
        case S_IFLNK: strcpy(p,"l");break;
        case S_IFREG: strcpy(p,"-");break;
        case S_IFSOCK: strcpy(p,"s");break;
           }
	for(int i=0;i<9;i++){
		if((m&(0400>>i))==0){
			//strcat(p,"-");
			p[i+1]='-';
			continue;
		}
	//	char s=a[i%3];
	//	strcat(p,&s);
		p[i+1]=a[i%3];
	}
	//printf("%s\n",p);
	return d;
}

你可能感兴趣的:(学习)