一、整体操作
打开目录文件
建立头文件"head.h"
dp = opendir(".");//"."表示当前目录文件
读取目录文件
readdir(dp);
eg:

①获取文件属性
②获取用户名
③获取同组的用户名
④获取该文件的字节数
⑤获取最后一次编辑该文件的时间(星期几,该月份的第几号,小时,分钟)
⑥该文件名
3.关闭目录文件
opendir(dp);
二、具体内容
创建头文件:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
具体函数:
#include "head.h"
int playfile(char *file)
{
struct stat buf;//获取文件属性
int ret = 0;
struct passwd *pwd = NULL;//getpwuid用法
struct group *grp = NULL;//getgrgid用法
struct tm *ptm = NULL;//time的用法
char *pmon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
ret = lstat(file, &buf);//获取文件属性成功,未成功ret结果为-1
if (-1 == ret)
{
perror("fail to lstat");
return -1;
}
if (S_ISREG(buf.st_mode))
{
putchar('-');
}
else if (S_ISDIR(buf.st_mode))
{
putchar('d');
}
else if (S_ISCHR(buf.st_mode))
{
putchar('c');
}
else if (S_ISBLK(buf.st_mode))
{
putchar('b');
}
else if (S_ISFIFO(buf.st_mode))
{
putchar('p');
}
else if (S_ISLNK(buf.st_mode))
{
putchar('l');
}
else if (S_ISSOCK(buf.st_mode))
{
putchar('s');
}
buf.st_mode & S_IRUSR ? putchar('r') : putchar('-');
buf.st_mode & S_IWUSR ? putchar('w') : putchar('-');
buf.st_mode & S_IXUSR ? putchar('x') : putchar('-');
buf.st_mode & S_IRGRP ? putchar('r') : putchar('-');
buf.st_mode & S_IWGRP ? putchar('w') : putchar('-');
buf.st_mode & S_IXGRP ? putchar('x') : putchar('-');
buf.st_mode & S_IROTH ? putchar('r') : putchar('-');
buf.st_mode & S_IWOTH ? putchar('w') : putchar('-');
buf.st_mode & S_IXOTH ? putchar('x') : putchar('-');
printf(" %ld", buf.st_nlink);//输出文件属性
pwd = getpwuid(buf.st_uid);
printf(" %s", pwd->pw_name);//输出路径名
grp = getgrgid(buf.st_gid);
printf(" %s", grp->gr_name);//输出路径名
printf(" %5ld", buf.st_size);//输出文件字节数
ptm = localtime(&buf.st_ctime);
printf(" %s %2d %02d:%02d", pmon[ptm->tm_mon], ptm->tm_mday, ptm->tm_hour, ptm->tm_min);//输出时间
printf(" %s", file);//输出本文件名
printf("\n");
return 0;
}
int mylist(void)
{
DIR *p = NULL;
struct dirent *tp = NULL;
p = opendir(".");
if (NULL == p)
{
perror("fail to opendir");
return -1;
}
while (1)
{
tp = readdir(p);
if (NULL == tp)
{
break;
}
if ('.' == tp->d_name[0])
{
continue;
}
playfile(tp->d_name);
}
closedir(p);
return 0;
}
int main(int argc, char const *argv[])
{
mylist();
return 0;
}
运行结果:
