#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h> // stat 函數所在的檔案
#include <dirent.h>
int main(void)
{
DIR *dp;
struct dirent *ep;
struct stat st;
char dirp[50];
printf("Please input a dir name:/n");
scanf("%s",&dirp); //讀入目錄名
dp=opendir("dirp"); //開啟所給目錄
printf("filename:/ttype:/tPermission/taccesstime/tlastmodtime/tsize/t");
if(dp!=NULL) //如果開啟目錄成功,則進行操作。
{
while(ep = readdir(dp)) //讀每一個目錄項的迴圈
{
if(ep->d_name[0]!='.') //判斷檔案名稱的第一個字元是否'.',如果是,表明是隱含檔案,我們不動,否則操作
{
//用stat函數開啟檔案的資訊,第一個參數是檔案的路徑,第二個參數存放檔案的資訊
if(stat(ep->d_name,&st)!=-1) //讀成功
{
printf("%s/t",ep->d_name);
if((st.st_mode&S_IFMT)==S_IFDIR) //判斷檔案的類型
printf("Directory/t"); //目錄
else if((st.st_mode&S_IFMT)==S_IFBLK) //塊檔案
printf("Block special file/t");
else if((st.st_mode&S_IFMT)==S_IFCHR) //特殊字元檔案
printf("character special file/t");
else if((st.st_mode&S_IFMT)==S_IFREG) //普通檔案
printf("Ordinary file/t");
else if((st.st_mode&S_IFMT)==S_IFIFO) //管道檔案
printf("pipefile file/t");
printf("%o/t",st.st_mode&0x1ff); //檔案的許可權
printf("%15s/t",ctime(st.st_atime)); //檔案建立時間
printf("%15s/t",ctime(st.st_mtime)); //檔案上次修改時間
printf("%ld/n",st.st_size); //檔案的大小
}
}
}
closedir(dp) //關閉目錄
}
else
puts("Couldn't open the directory./n"); //開啟不成功時,輸出不能開啟路徑
return 0;
}