2025年4月11日 星期五 乙巳(蛇)年 正月十二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

怎样使用C语言列出某个目录下的文件?

时间:12-30来源:作者:点击数:113

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" );
  • }

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门