linux文件操作

 #include <stdio.h>
#include <stdlib.h>
#include <sys/dir.h>
#include <sys/stat.h>
#include <string.h>
/* 判斷是否爲目錄 */
int IS_DIR(const char* path)
{
         struct stat st;
         lstat(path, &st);
         return S_ISDIR(st.st_mode);
}

/* 獲得當前路徑 */

char* _getcwd(char* _DstBuf,int _SizeInBytes)
{
        if( _DstBuf == NULL )
                return NULL;
        int count = readlink("/proc/self/exe",_DstBuf,_SizeInBytes);
        if( count < 0 || count >= _SizeInBytes )
        {
                printf("Get Cur Path Error!\n");
                return NULL;
        }
        _DstBuf[count] = '\0';
        return _DstBuf;
}

 

/* 遍歷文件夾de遞歸函數 */
void List_Files_Core(const char *path, int recursive)
{
     DIR *pdir;
     struct dirent *pdirent;
     char temp[256];
     pdir = opendir(path);
     if(pdir)
     {

         while(pdirent = readdir(pdir))
         {
               /* 跳過"."和".." */
               if(strcmp(pdirent->d_name, ".") == 0
                         || strcmp(pdirent->d_name, "..") == 0)
                    continue;

               sprintf(temp, "%s/%s", path, pdirent->d_name);

               printf("%s\n", temp);
               /* 當temp爲目錄並且recursive爲1的時候遞歸處理子目錄 */
               if(IS_DIR(temp) && recursive)
               {
                       List_Files_Core(temp, recursive);
               }
         }

      }
     else
     {
         printf("opendir error:%s\n", path);
      }
      closedir(pdir);

}

 

/* 遍歷文件夾的驅動函數 */
void List_Files(const char *path, int recursive)
{
          int len;
          char temp[256];

          /* 去掉末尾的'/' */
          len = strlen(path);
          strcpy(temp, path);
          if(temp[len - 1] == '/') temp[len -1] = '\0';

          if(IS_DIR(temp))
          {
                   /* 處理目錄 */
                   List_Files_Core(temp, recursive);
          }
         else   /* 輸出文件 */
         {
                  printf("%s\n", path);
         }
}

 

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