查找目录下所有文件中特定字符串

 
  1.         private void GetFileNames(string path,out ArrayList list)
  2.         {
  3.             list = new ArrayList();
  4.             if(!Directory.Exists(path)) return;
  5.             string[] fis=Directory.GetFiles(path);
  6.             Regex reg=new Regex(@"x/w{16}");
  7.             foreach(string s in fis)
  8.             {
  9.                 StreamReader sr=new StreamReader(s,Encoding.Default);
  10.                 string text=sr.ReadToEnd();
  11.                 sr.Close();
  12.                 foreach(Match m in reg.Matches(text))
  13.                 {
  14.                  list.Add(m.Value);
  15.                 }
  16.             }
  17.         }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下步骤来完成用C语言打开特定目录文件查找特定字符串并修改的任务: 1. 使用`opendir`函数打开指定目录。 2. 使用`readdir`函数遍历目录的所有文件。 3. 对于每个文件,使用`fopen`函数打开并读取文件内容。 4. 使用`strstr`函数查找文件内容是否包含特定字符串。 5. 如果找到特定字符串,可以使用`fseek`函数找到字符串所在的位置,然后使用`fwrite`函数将修改后的字符串写回文件。 6. 关闭文件并继续遍历下一个文件,直到目录的所有文件都被遍历完毕。 7. 关闭目录并结束程序。 以下是一份示例代码,可以根据具体需求进行修改: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> void search_and_replace(const char *filename, const char *search, const char *replace) { FILE *fp = fopen(filename, "r+"); if (fp == NULL) { printf("Failed to open file: %s\n", filename); return; } char buf[1024]; size_t search_len = strlen(search); size_t replace_len = strlen(replace); while (fgets(buf, sizeof(buf), fp) != NULL) { char *pos; while ((pos = strstr(buf, search)) != NULL) { fseek(fp, pos - buf, SEEK_CUR); fputs(replace, fp); memmove(pos + replace_len, pos + search_len, strlen(pos + search_len) + 1); rewind(fp); fseek(fp, strlen(buf) - strlen(pos + search_len), SEEK_CUR); } } fclose(fp); } int main() { const char *dir_path = "/path/to/directory"; const char *search_str = "hello"; const char *replace_str = "world"; DIR *dir = opendir(dir_path); if (dir == NULL) { printf("Failed to open directory: %s\n", dir_path); return 1; } struct dirent *entry; while ((entry = readdir(dir)) != NULL) { if (entry->d_type == DT_REG) { char path[1024]; snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name); search_and_replace(path, search_str, replace_str); } } closedir(dir); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值