最近再看linux方面的知識,話說如今linux前途很好吖,,,因此我也試着學linux,前幾天從oschina裏看了一個linux c遍歷目錄的源代碼,但發現子目錄沒有進行遍歷,因此進行了修改,但願能多交流學習,本人新手,願共同進步,高手勿噴~謝拉 linux
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
int trave_dir(char *path,int i)
{
DIR *d;
struct dirent *file;
struct stat buf;
if(!(d=opendir(path)))
{
printf("error opendir %s!!!\n",path);
return -1;
}
chdir(path); //必定要打開文件夾,不打開會出現錯誤
while((file=readdir(d)) != NULL)
{
lstat(file->d_name,&buf);
if(!(S_IFDIR&buf.st_mode))
{
printf("%*s%s\n",i,"",file->d_name);//printf特殊用法 格式輸出
printf("\t\tfile size=%d\n",buf.st_size);
printf("\t\tfile last modify time=%s\n",asctime(gmtime(&buf.st_mtime)));//先轉化成格林威治時間,而後返回tm結構,接着用asctime轉化成標準時間(這裏 不知到有沒有更好的方法)
}
else
{
if(strcmp(file->d_name,".")==0||strcmp(file->d_name,"..")==0)
continue;
printf("%*s%s(dir)\n",i,"",file->d_name);
printf("\t\tfile last modify time=%s\n",asctime(gmtime(&buf.st_mtime)));
trave_dir(file->d_name,i+2);
}
}
chdir("..");
closedir(d);
return 0;
}
int main()
{
int i;
trave_dir(".",0);
return 0;
} 學習