编写display.c和search.c文件共同完成该任务
编写search.h作为同名头文件声明全局变量和查找文件函数
search.h源代码:
#includeint file_search(char *path, char *gjz); //声明文件查找函数 extern char filename[256][256]; extern int len; //在*.h文件中使用extern来声明变量,可以避免后续编译出现一些错误
*.h文件中写函数声明,*.c文件中实现,这样分离之后,如果其他c文件需要调用其中的函数只要包含同名的h头文件即可:#include "*.h",注意必须用双引号,不能用尖括号,使用双引号会优先调用当前目录下的头文件。
把具体相同功能的函数放置在一个h头文件中声明也有助于分类。
search.c源代码:
#include#include #include #include #include #include "search.h" //使用search.h中声明的变量,定义其中声明的函数 char filename[256][256]; //存放返回的文件名 int len; int file_search(char *path, char *gjz) { DIR *d; //声明一个句柄 len = 0; struct dirent *file; //readdir函数的返回值就存放在这个结构体中 if(!(d = opendir(path))) //检查该目录是否存在 { printf("error opendir %s!n",path); return -1; } while((file = readdir(d)) != NULL) //遍历目录 { //把当前目录.,上一级目录..及隐藏文件都去掉 if(strncmp(file->d_name, ".", 1) == 0) //通过ASCⅡ码比较两个字符串是否相同,相同则返 回0,参数"1"表示只比较1个字符 continue; if(strstr(file->d_name,gjz)) //检查右边字符串是否为左边字符串的子串() { strcpy(filename[len++], file->d_name); //保存遍历到的文件名 } } closedir(d); return 0; }
display.c源代码
#include#include "search.h" int main() { int i; file_search("./text", "d"); //"./text"为查找的目录,"d"为文件名关键字 for(i = 0; i < len; i++) { printf("%sn", filename[i]); } printf("n"); return 0; }
编译命令如下:
gcc display.c search.c -o display_searchfile //编译生成可执行文件
编写makefile文件:
display_searchfile:display.c search.c //注意冒号要用英文冒号 gcc display.c search.c -o display_searchfile //开头用Tab缩进 clean: rm -f display_searchfile //开头用Tab缩进



