发布网友
共2个回答
热心网友
用C语言列出目录下的文件,在linux下可采用readdir()函数来实现,代码实现过程为:
打开目录
循环读目录,输出目录下文件
关闭目录指针
参考代码:
#include <dirent.h>在windows下,代码如下:
#include <io.h>相关函数说明:
long _findfirst( char *filespec, struct _finddata_t *fileinfo );
热心网友
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_BLOCKvoid 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 listall files in the directory, including system files, hiddenfiles, and subdirectory names. * /ret_code = _dos_findfirst(" *. * ", 0xFF, &f_block);/* The _dos_findfirst() function returns a 0 when it is successfuland 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