#include
#include
#include
#include
#include
#include
#include
#include
#include
void get_file_permission(unsigned int tmp_mod, char file_mod[], int num)
{
bzero(file_mod,num);
unsigned int flag = 1<<9;char str[4]="rwx";
for(int i=0; i<9; i++)
{
flag >>= 1;if(!(tmp_mod & flag))
{
file_mod[i] = '-';
}else
{
file_mod[i] = str[i%3];
}}
}
char get_file_type(unsigned int tmp_filetype)
{
char file_type[8] = "pcdb-ls";
unsigned int num_filetype[7] = {01,02,04,06,010,012,014};
for(int i=0; i<8; i++)
{
if(0 == (tmp_filetype ^ num_filetype[i]))
{
return file_type[i];
}
}
}int main(int argc, const char *argv[])
{
if(argc <2)
{
fprintf(stderr, "请从命令行输入文件名\n");
return -1;
}struct stat buf;
if(stat(argv[1], &buf) < 0)
{
perror("stata");
return -1;
}//文件的类型和权限
//printf("st_mode : %o.\n", buf.st_mode);
char file_mod[10];//将buf.st_mode中的文件权限提取出来
unsigned int tmp_mod = buf.st_mode & ~((~1)<<10);
unsigned int tmp_filetype = (buf.st_mode & S_IFMT) >> 12;
char c = get_file_type(tmp_filetype);
printf("%c", c);
//将文件权限由数字转化为字母
get_file_permission(tmp_mod, file_mod, 10);//打印转换后的文件权限
printf("%s ", file_mod);//硬连接数
printf("%ld ", buf.st_nlink);//文件所属用户
//printf("%d ", buf.st_uid);
struct passwd *tmp_usname = getpwuid(buf.st_uid);
printf("%s ", tmp_usname->pw_name);//文件所属组名
//printf("%d ", buf.st_gid);
struct group *tmp_groupname = getgrgid(buf.st_gid);
printf("%s ", tmp_groupname->gr_name);//文件大小
printf("%ld ", buf.st_size);//时间
time_t t = buf.st_ctime;
struct tm *tmp_time = localtime(&t);
printf("%d %d %d:%d ", tmp_time->tm_mon+1, tmp_time->tm_mday, \tmp_time->tm_hour , tmp_time->tm_min);
printf("%s\n", argv[1]);return 0;
}