实现linux ls -l的功能(简易模仿 欢迎指正 粗糙勿喷)

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

char* file_time(time_t t,char* str)
{
	struct tm* it = localtime(&t);
	sprintf(str,"%4d-%02d-%02d %02d:%02d:%02d",it->tm_year+1900,it->tm_mon+1,it->tm_mday,it->tm_hour,it->tm_min,it->tm_sec);
	return str;
}

char* file_mode(mode_t m,char* str)
{
	if(S_ISREG(m))
		str[0] = '-';
	else if(S_ISDIR(m))
		str[0] = 'd';
	else if(S_ISCHR(m))
		str[0] = 'c';
	else if(S_ISBLK(m))
		str[0] = 'b';
	else if(S_ISFIFO(m))
		str[0] = 'q';
	else if(S_ISLNK(m))
		str[0] = 'l';
	else if(S_ISSOCK(m))
		str[0] = 's';
	else 
		str[0] = '?';

	str[1] = '\0';

	strcat(str,S_IRUSR&m?"r":"-");
	strcat(str,S_IWUSR&m?"w":"-");
	strcat(str,S_IXUSR&m?"x":"-");

	strcat(str,S_IRGRP&m?"r":"-");
	strcat(str,S_IWGRP&m?"w":"-");
	strcat(str,S_IXGRP&m?"x":"-");
	
	strcat(str,S_IROTH&m?"r":"-");
	strcat(str,S_IWOTH&m?"w":"-");
	strcat(str,S_IXOTH&m?"x":"-");

	return str;
}

int main()
{
    DIR* dp = opendir(".");
	if(NULL == dp)
	{
		perror("opendir");
		return -1;
	}
	struct dirent* de = readdir(dp);
	struct stat buf = {};
	
	char str[50] = {};
	for(de; NULL!=de;de=readdir(dp))
	{
	    stat(de->d_name,&buf);
		printf("%s ",file_mode(buf.st_mode,str));
		printf("zhizhen ");
		printf("zhizhen ");
	    printf("%s ",file_time(buf.st_mtime,str));
	    printf("%s\n",de->d_name);
	}

}

上一篇:微信开发配置JSSDK,注入权限验证,以及invalid signature签名错误解决


下一篇:MATLAB_9-模式识别笔记