- 了解所需要使用的函数,使用shell命令 man 来查看它们的使用方法
- struct dirent *readdir(DIR *dirp);int closedir(DIR *dirp);int stat(const char *path, struct stat *buf);struct passwd *getpwuid(uid_t uid);
- 结构体:
- struct dirent{xxx};
struct stat{xxx}
- 文件类型
{
常规文件:S_ISREG '-'
目录:S_ISDIR 'd'
字符设备:S_ISCHR 'c'
块设备:S_ISBLK 'b'
管道:S_ISFIFO 'p'
套接字:S_ISSOCK 's'
符号链接:S_ISLNK 'l'
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
#include <unistd.h>
#include <pwd.h>
int main(int argc, char *argv[])
{
DIR *p = opendir(argv[1]);
while(1)
{
struct stat mybuf;
struct dirent *q = readdir(p);
if(q == NULL)
return -1;
else if(strncmp(q->d_name,".",1)==0)
continue;
stat(q->d_name,&mybuf);
if(S_ISREG(mybuf.st_mode))
printf("-");
if(S_ISDIR(mybuf.st_mode))
printf("d");
if(S_ISCHR(mybuf.st_mode))
printf("c");
if(S_ISBLK(mybuf.st_mode))
printf("b");
if(S_ISFIFO(mybuf.st_mode))
printf("p");
if(S_ISSOCK(mybuf.st_mode))
printf("s");
if(S_ISLNK(mybuf.st_mode))
printf("l");
printf("%c", (mybuf.st_mode & (0x1<<8) )?'r':'-');
printf("%c", (mybuf.st_mode & (0x1<<7) )?'w':'-');
printf("%c", (mybuf.st_mode & (0x1<<6) )?'x':'-');
printf("%c", (mybuf.st_mode & (0x1<<5) )?'r':'-');
printf("%c", (mybuf.st_mode & (0x1<<4) )?'w':'-');
printf("%c", (mybuf.st_mode & (0x1<<3) )?'x':'-');
printf("%c", (mybuf.st_mode & (0x1<<2) )?'r':'-');
printf("%c", (mybuf.st_mode & (0x1<<1) )?'w':'-');
printf("%c ", (mybuf.st_mode & (0x1) )?'x':'-');
printf("%ld ", mybuf.st_nlink);
struct passwd *w = getpwuid(mybuf.st_uid);
printf("%s ", w->pw_name);
struct passwd *m = getpwuid(mybuf.st_gid);
printf("%s ", m->pw_name);
printf("%ld ", mybuf.st_size);
struct tm *k = localtime(&mybuf.st_mtime);
printf("%d月 ", k->tm_mon+1);
printf("%d ", k->tm_mday);
printf("%d:", k->tm_hour);
printf("%d ", k->tm_min);
printf("%s\n",q->d_name);
}
return 0;
}