C语言列出某个目录下的文件

本文介绍了如何使用C语言及DOS API实现自定义dir_list()函数,通过调用_dos_findfirst()和_dos_findnext()函数遍历指定目录下所有文件,并打印文件信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C语言本身没有提供象dir_list()这样的函数来列出某个目录下所有的文件。不过,利用C语言的几个目录函数,你可以自己编写一个dir_list()函数。   

首先,头文件dos.h定义了一个find_t结构,它可以描述DOS下的文件信息,包括文件名、时间、日期、大小和属性。其次,C编译程序库中有_dos_findfirst()和_dos_findnext()这样两个函数,利用它们可以找到某个目录下符合查找要求的第一个或下一个文件。   

dos_findfirst()函数有三个参数,第一个参数指明要查找的文件名,例如你可以用“*.*”指明要查找某个目录下的所有文件。第二个参数指明要查找的文件属性,例如你可以指明只查找隐含文件或子目录。第三个参数是指向一个find_t变量的指针,查找到的文件的有关信息将存放到该变量中。   

dos_findnext()函数在相应的目录中继续查找由_dos_findfirst()函数的第一个参数指明的文件。_dos_findnext()函数只有一个参数,它同样是指向一个find_t变量的指针,查找到刚文件的有关信息同样将存放到该变量中。

利用上述两个函数和find_t结构,你就可以遍历磁盘上的某个目录,并列出该目录下所有的文件,请看下例:   
#include <stdio.h>
#include <direct.h>
#include <dos.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
typedef struct find_t FILE_BLOCK
void main(void);
void main(void)
{
      FILE_BLOCK f-block;         /* Define the find_t structure variable * /
      int   ret_code;             / * Define a variable to store the return codes * /
      / * Use the "*.*" file mask and the 0xFF attribute mask to list
           all files in the directory, including system files, hidden
           files, and subdirectory names.  * /
      ret_code = _dos_findfirst(" *. * ", 0xFF, &f_block);
      /* The _dos_findfirst() function returns a 0 when it is successful
         and has found a valid filename in the directory.  * /
     while (ret_code == 0)
     {
          /* Print the file's name * /
          printf(" %-12s\n, f_block, name);
          / * Use the -dos_findnext() function to look
               for the next file in the directory.  * /
          ret_code = _dos_findnext (&f_block);
     }
     printf("\nEnd of directory listing. \n" );
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值