11.test.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void get_file(mode_t mode)
{
int a = 0400;
char arr[4] = "rwx";
for (int i=0; i<9; i++)
{
if ((mode & a) != 0)
{
putchar(arr[i%3]);
}else
{
putchar('-');
}
a = a>>1;
}
}
char get_filetype(mode_t mode)
{
if (S_ISREG(mode))
return '-';
else if(S_ISDIR(mode))
return 'd';
else if(S_ISCHR(mode))
return 'c';
else if(S_ISBLK(mode))
return 'b';
else if(S_ISFIFO(mode))
return 'p';
else if(S_ISLNK(mode))
return 'd';
else if(S_ISSOCK(mode))
return 'd';
11.test.h
#ifndef __11TEST_H__
#define __11TEST_H__
void get_file(mode_t mode);
char get_filetype(mode_t mode);
#endif
14.test.c
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "11test.h"
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <dirent.h>
#include <errno.h>
int main(int argc, const char *argv[])
{
//打开一个目录
DIR* dp = opendir("./");
if (NULL == dp)
{
perror("opendir");
return -1;
}
//读取目录
struct dirent* rp = NULL;
int i = 1;
while(1)
{
rp = readdir(dp);
if (NULL==rp)
{
if (errno != 0)
{
perror("readdir");
return -1;
}
else
{
printf("目录读取完毕\n");
break;
}
}
struct stat buf;
if (stat(rp->d_name, &buf)<0)
{
perror("stat");
return -1;
}
char type = 0;
//文件的类型及权限
type = get_filetype(buf.st_mode);
printf("%c",type);
//printf("mode: %o\n",buf.st_mode);
get_file(buf.st_mode);
//文件的硬件接数
printf(" %ld ",buf.st_nlink);
//文件所属用户
//printf("uid: %d ",buf.st_uid);
struct passwd *uid = getpwuid(buf.st_uid);
printf("%s ",uid->pw_name);
//文件所属组用户
//printf("gid: %d ",buf.st_gid);
struct group *gid = getgrgid(buf.st_gid);
printf("%s ",gid->gr_name);
//文件的大小
printf("%-7ld ",buf.st_size);
//文件的时间
//printf("time: %ld",buf.st_ctime);
struct tm *info = NULL;
info = localtime(&buf.st_ctime);
printf("%d %d %02d:%02d",info->tm_mon+1,\
info->tm_mday,info->tm_hour,info->tm_min);