...
#include<stdio.h>
#include<dirent.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
/*
* $ls -la ~
* total 460
* drwxr-xr-x 31 linux linux 4096 10月 27 17:27 .
* drwxr-xr-x 3 root root 4096 9月 22 2012 ..
* -rw------- 1 linux linux 3126 10月 5 12:56 altvimrc
* -rw-rw-r-- 1 linux linux 102 10月 27 11:31 .apport-ignore.xml
* -rw------- 1 linux linux 20110 10月 27 15:47 .bash_history
* -rw-r--r-- 1 linux linux 220 9月 22 2012 .bash_logout
*/
int main(int argc, const char *argv[])
{
//打開目錄流
//迴圈讀取其中的文件名,
//將文件名使用stat()讀取屬性,並做相應解析
//寫入到文件
DIR* dp=opendir(".");
struct dirent* Dir;
struct stat File;
while(Dir=readdir(dp)){
stat(Dir->d_name,&File);
char prot[11]={0};
//獲取文件類型並解析
switch (File.st_mode&S_IFMT){
case S_IFSOCK:
strcpy(prot,"s");
break;
case S_IFLNK:
strcpy(prot,"l");
break;
case S_IFREG:
strcpy(prot,"-");
break;
case S_IFBLK:
strcpy(prot,"b");
break;
case S_IFDIR:
strcpy(prot,"d");
break;
case S_IFCHR:
strcpy(prot,"c");
break;
case S_IFIFO:
strcpy(prot,"p");
break;
}
//獲取文件許可權並解析
//處理屬主許可權
if(S_IRUSR==((File.st_mode&S_IRWXU)&S_IRUSR))
strcat(prot,"r");
else
strcat(prot,"-");
if(S_IWUSR==((File.st_mode&S_IRWXU)&S_IWUSR))
strcat(prot,"w");
else
strcat(prot,"-");
if(S_IXUSR==((File.st_mode&S_IRWXU)&S_IXUSR))
strcat(prot,"x");
else
strcat(prot,"-");
//處理屬組許可權
if(S_IRGRP==((File.st_mode&S_IRWXG)&S_IRGRP))
strcat(prot,"r");
else
strcat(prot,"-");
if(S_IWGRP==((File.st_mode&S_IRWXG)&S_IWGRP))
strcat(prot,"w");
else
strcat(prot,"-");
if(S_IXGRP==((File.st_mode&S_IRWXG)&S_IXGRP))
strcat(prot,"x");
else
strcat(prot,"-");
//處理其他許可權
if(S_IROTH==((File.st_mode&S_IRWXO)&S_IROTH))
strcat(prot,"r");
else
strcat(prot,"-");
if(S_IWOTH==((File.st_mode&S_IRWXO)&S_IWOTH))
strcat(prot,"w");
else
strcat(prot,"-");
if(S_IXOTH==((File.st_mode&S_IRWXO)&S_IXOTH))
strcat(prot,"x");
else
strcat(prot,"-");
//獲取文件硬鏈接數
//獲取文件屬主的名
struct passwd* pwd=getpwuid(File.st_uid);
//獲取文件屬主的組名
struct group* grp=getgrgid(File.st_gid);
//獲取文件的大小
//獲取文件的mtime
struct tm* myTime;
myTime=localtime(&File.st_mtime);
printf("%s %d %s %s %5ld %d月 %d %02d:%02d %s\n",
prot,
File.st_nlink,
pwd->pw_name,
grp->gr_name,
File.st_size,
myTime->tm_mon+1,
myTime->tm_mday,
myTime->tm_hour,
myTime->tm_min,
Dir->d_name
);
}
return 0;
}