程序:
statfunc.h:
#ifndef __STATFUNC_H__
#define __STATFUNC_H__
void get_filepermission(mode_t mode);
char get_filetype(mode_t mode);
#endif
statfunc.c:
#include<stdio.h>
#include<fcntl.h>
#include "statfunc.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
void get_filepermission(mode_t mode)
{
int j=0400;
char arr[3]={'r','w','x'};
for(int i=0;i<9;i++)
{
if((mode&j)!=0)
{
putchar(arr[i%3]);
}
else
{
printf("-");
}
j=j>>1;
}
printf(" ");
}
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 'l';
else if(S_ISSOCK(mode))
return 's';
}
readdir.c:
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <fcntl.h>
#include "statfunc.h"
int main(int argc, const char *argv[])
{
DIR *dp=opendir("./");
if(NULL==dp)
{
perror("opendir");
return -1;
}
//读取目录
int i=0;
while(1)
{
struct dirent *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);
get_filepermission(buf.st_mode);
//文件硬连接数
printf("%ld ",buf.st_nlink);
//文件所属用户
struct passwd*pwd=getpwuid(buf.st_uid);
if(NULL==pwd)
{
perror("getpwuid");
return -1;
}
printf("%s ",pwd->pw_name);
//文件所属组用户
struct group* grp=getgrgid(buf.st_gid);
if(NULL==grp)
{
perror("getpwuid");
return -1;
}
printf("%s ",grp->gr_name);
//文件的大小
printf("%-7ld ",buf.st_size);
//文件的时间
struct tm *t1=NULL;
t1=localtime(&buf.st_atime);
printf("%d %d %02d:%02d ",t1->tm_mon+1,t1->tm_mday,t1->tm_hour,t1->tm_min);
//文件名
printf("%s\n",rp->d_name);
}
if(closedir(dp)<0)
{
perror("closedir");
return -1;
}
return 0;
}
运行效果:
drwxrwxr-x 6 ubuntu ubuntu 4096 12 8 09:24 ..
-rwxr-xr-x 1 ubuntu ubuntu 13128 12 8 19:07 a.out
-rw-r--r-- 1 ubuntu ubuntu 927 12 8 17:24 fork.c
-rw-r--r-- 1 ubuntu ubuntu 95 12 8 13:41 1.c
-rwxr-xr-x 1 ubuntu ubuntu 354084 12 8 16:27 1.txt
-rw-r--r-- 1 ubuntu ubuntu 1527 12 8 19:07 readdir.c
drwxr-xr-x 2 ubuntu ubuntu 4096 12 8 19:07 .
-rw-r--r-- 1 ubuntu ubuntu 659 12 8 18:53 statfunc.c
-rw-r--r-- 1 ubuntu ubuntu 126 12 8 18:53 statfunc.h
目录读取完成