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
原文地址:https://www.cnblogs.com/surgewong/p/3351577.html