自己寫的一個LINUX 下目錄文件遍歷程序

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/types.h>
int lsdir(char *filepath , int ntap)
{
 struct stat  buf ;
 struct dirent *direntp;
 DIR *dir;
 char path[100];
 int i;
 if((dir =  opendir(filepath))==NULL)
  {
   printf("opendir error!/n");
   exit (0);
  }
 
 char tb[100];
 memset(tb,'/0',100);
 for(i=0;i<ntap;i++)
  {
   tb[i]='/t';
  }
    while((direntp = readdir(dir)) != NULL)
    {
     if(strcmp( ".",direntp->d_name) == 0 || strcmp( "..",direntp->d_name) == 0)
   {
    continue;
   }   
      strcpy(path,filepath);
         strcat(path,"/");
  strcat(path,direntp->d_name);
  //printf("path=%s/n",path);
         stat(path,&buf);//獲取文件屬性
         //printf("aaaaaa/n");
         //filepath = strcat(filepath,direntp->d_name); //獲取新的文件路徑
  
         //printf("%s/n",direntp->d_name);

         if(S_ISDIR(buf.st_mode))
  {
   //排除當前目錄和上級目錄
   //如果是子目錄,遞歸調用函數本身,實現子目錄中文件遍歷
   printf( "%s%s//n", tb, direntp->d_name);
   //遞歸調用,遍歷子目錄中文件
   lsdir( path, ntap+1); 
  }
  else
  {
   printf( "%s%s/n", tb, direntp->d_name);
  }       
 }
 closedir(dir);
 return 1;
}
 


int main(int argc,char *argv[])
{
  lsdir(argv[1],0);
  return 1;
       

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章