C語言下文件目錄查看


C語言下文件目錄遍歷通常會用到下面這些函數

  _access()        /* 判斷文件或文件夾路徑是否合法 */

  _chdir()     /* 切換當前工作目錄 */

  _findfirst()    /* 查找第一個符合要求的文件或目錄 */

  _findnext()     /* 查找下一個 */

  _findclose()    /* 關閉查找 */

與此同時還會使用到 struct _finddata_t 結構體

   struct _finddata_t  { 
             unsigned attrib;                       /* 表示文件的屬性 */

             time_t time_create;                 /* 表示文件創建的時間 */  

             time_t time_access;                 /* 表示文件最后訪問的時間 */

             time_t time_write;                   /* 表示文件最后寫入的時間 */ 

            _fsize_t size;                            /* 表示文件的大小 */
             char name[FILENAME_MAX];       /* 表示文件的名稱 */

        };

文件屬性(attrib)的值可以取下面的值:

         #define _A_NORMAL 0x00000000
         #define _A_RDONLY 0x00000001
         #define _A_HIDDEN 0x00000002
         #define _A_SYSTEM 0x00000004
         #define _A_VOLID 0x00000008
         #define _A_SUBDIR 0x00000010
         #define _A_ARCH  0x00000020

在io.h文件中FILENAME_MAX 被定義為260

下面給出的是一個簡單的小程序用於列出目錄C:\ 下的文件夾的名字

(這里建議大家使用斜杠'/',少用'\',windows下程序能夠自動解析'/',使用反斜杠時需要使用"\\")

 1 #include <dir.h>
 2 #include <stdio.h>
 3 #include <io.h>
 4 #include <string.h>
 5 
 6 int main(int argc, char* argv[])
 7 {
 8     char path[100] = "C:/";
 9     
10     struct _finddata_t fa;
11     long handle;
12     
13     if((handle = _findfirst(strcat(path,"*"),&fa)) == -1L)
14     {
15         printf("The Path %s is wrong!\n",path);
16         return 0;
17     }
18     
19     do
20     {
21         if( fa.attrib == _A_SUBDIR && ~strcmp(fa.name,".")&& ~strcmp(fa.name,".."))
22             printf("The subdirectory is %s\n",fa.name);
23     }while(_findnext(handle,&fa) == 0); /* 成功找到時返回0*/ 
24     
25     _findclose(handle);
26     
27     return 0;    
28 } 
View Code

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM