#include <stdio.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
void getfilepath(char *filename)
{
int len = strlen(filename);
int i = len;
if(filename[i] != '/'){
i--;
}
filename[i+1]='\0';
}
void getfileinfo(char *filename, char *d_name)
{
struct stat fileinfo;
if(stat(filename, &fileinfo)<0)
perror("stat");
//判断文件类型
if(S_ISREG(fileinfo.st_mode))
printf("-");
else if(S_ISDIR(fileinfo.st_mode))
printf("d");
else if(S_ISCHR(fileinfo.st_mode))
printf("c");
else if(S_ISBLK(fileinfo.st_mode))
printf("b");
else if(S_ISFIFO(fileinfo.st_mode))
printf("p");
else if((fileinfo.st_mode & S_IFMT) == S_IFLNK)
printf("l");
else if(S_ISSOCK(fileinfo.st_mode))
printf("s");
//获取文件权限
int i;
char str[] = "xwr-";
for(i=8; i >=0; i--)
if(fileinfo.st_mode & 1<<i)
printf("%c",str[i%3]);
else
printf("%c", str[3]);
printf(" %3u ", fileinfo.st_nlink);
printf("%s ", getpwuid(fileinfo.st_uid)->pw_name);
printf("%s ", getgrgid(fileinfo.st_gid)->gr_name);
printf("%8ld ", fileinfo.st_size);
struct tm *pt;
pt = localtime(&fileinfo.st_atime);
printf("%02d-%02d %02d:%02d ", pt->tm_mon+1, pt->tm_mday,
pt->tm_hour, pt->tm_min);
//printf("%s", filename);
printf("%s", d_name);
printf("\n");
}
int main(int argc, char **argv)
{
if(argc <2){
exit(1);
}
//int fd;
//fd = open(argv[1], O_RDWR);
DIR *pd;
if((pd = opendir(argv[1]))== NULL){
perror("opendir");
exit(1);
}
struct dirent *dir;
char path[255] ,fullname[255];
strcpy(path, argv[1]);
getfilepath(path);
while((dir=readdir(pd)) != NULL){
bzero(fullname,255);
strcpy(fullname,path);
//printf("%s\n", dir->d_name);
strcat(fullname,dir->d_name);
//printf("%s\n", fullname);
//getfileinfo(dir->d_name);
getfileinfo(fullname, dir->d_name);
}
//perror("readdir");
return 0;
}
运行结果: