文件夹搜索程序 c语言,C语言按关键字搜索文件夹中文件的方法

本文实例讲述了C语言按关键字搜索文件夹中文件的方法。分享给大家供大家参考。具体实现方法如下:

方法1:

#include

#include

#include

using namespace std;

void filesearch(string path,string mode)

{

struct _finddata_t filefind;

if(path[path.size()-1]=='\\')

path.resize(path.size()-1);

string curr=path+"\\*.*";

int done=0,handle;

if((handle=_findfirst(curr.c_str(),&filefind))==-1)

return;

while(!(done=_findnext(handle,&filefind)))

{

if(!strcmp(filefind.name,".."))

continue;

curr=path+"\\"+filefind.name;

if(strstr(filefind.name,mode.c_str()))

cout<

if (_A_SUBDIR==filefind.attrib)

filesearch(curr,mode);

}

_findclose(handle);

}

void main()

{

string path,mode;

cout<

cin>>path;

cout<

cin>>mode;

filesearch(path,mode);

}

方法2:

#include

#include

#include

#define SIZE 12

void find_creat_file(char *);

int main(void)

{

char filename[SIZE];

strcpy(filename,"filename");

find_creat_file(filename);

getch();

return 0;

}

void find_creat_file(char *filename)

{

struct ffblk ffblk;

int done;

done=findfirst("d:\\filename",&ffblk,0);

if(done==0)

return 0;

else

mkdir("d:\\filename");

}

希望本文所述对大家的C语言程序设计有所帮助。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一份实现按关键字检索文件的代码,你可以参考一下: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #define MAX_PATH_LEN 1024 #define MAX_KEYWORD_LEN 128 void search_files(const char *dir_path, const char *keyword); int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s dir_path keyword\n", argv[0]); exit(1); } search_files(argv[1], argv[2]); return 0; } void search_files(const char *dir_path, const char *keyword) { DIR *dir; struct dirent *entry; char file_path[MAX_PATH_LEN]; char buf[MAX_KEYWORD_LEN]; FILE *fp; if ((dir = opendir(dir_path)) == NULL) { perror("opendir"); exit(1); } while ((entry = readdir(dir)) != NULL) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } snprintf(file_path, MAX_PATH_LEN, "%s/%s", dir_path, entry->d_name); if ((fp = fopen(file_path, "r")) == NULL) { perror("fopen"); exit(1); } while (fgets(buf, MAX_KEYWORD_LEN, fp) != NULL) { if (strstr(buf, keyword) != NULL) { printf("%s\n", file_path); break; } } fclose(fp); } closedir(dir); } ``` 这个程序的思路比较简单,就是先用 opendir 打开指定的文件夹,然后逐个读取文件,对于每个文件,我们再用 fopen 打开,并逐行读取,检查每行是否包含指定的关键字。如果包含,就输出该文件的路径。最后用 closedir 关闭文件夹即可。 需要注意的是,这个程序只能检索文本文件,对于二进制文件等其他类型的文件是无法处理的。如果需要支持其他类型的文件,还需要进行适当的扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值