Linux搜索指定文件夹并打开最符合搜索目标名称的文件

来源:互联网 发布:i代表什么矩阵 编辑:程序博客网 时间:2024/05/18 00:19

先大致参考

关于Linux相对路径的问题:http://blog.csdn.net/yongqiangyue/article/details/7707854

关于搜索Linux文件目录下文件http://myswirl.blog.163.com/blog/static/513186422010102495152843/

open、openat函数参考UNIX环境高级编程和http://blog.csdn.net/shanshanpt/article/details/39927553与http://blog.csdn.net/wang1902568721/article/details/47796173

这里面说与目标文件名“最符合”,可自由定义最符合的条件:相同、包含、通配符匹配之类都可以,大不了加个匹配算法

#include <stdio.h>  #include <sys/types.h>  #include <dirent.h>  #include <sys/stat.h>  #include <fcntl.h>  #define BufferSize 16  /*  *搜索"data"文件夹下的文件,如果有文件名为fileName的文件则获得该文件的路径,存入字符串file中  */  int fileDescreption(char* filePath, char *fileName){      DIR *dp;      struct dirent *dirp;      if((dp = opendir(filePath)) == NULL){          printf("Can't open filePath:%s\n", filePath);          return -1;      }        while((dirp = readdir(dp)) != NULL){          if(strcmp(dirp->d_name,fileName) == 0){              fileName = dirp->d_name;              printf("fd:%s\n", fileName);              break;          }      }      closedir(dp);      char file[256] = {0};      sprintf(file,"%s%s%s",filePath,"/",fileName);//最终file为data/test,这里也可以改成调用openat函数      int fd = open(file,O_RDONLY);      return fd;  }    void readFile(int fd){      if(fd == -1){          perror("open file");          return;      }      char buf[BufferSize] = {0};      while(read(fd,buf,sizeof(buf)) > 0){                }      buf[BufferSize-1] = '\0';      printf("%s",buf);      close(fd);  }    int main(){      char *fileName = "test";      char *filePath = "data";      readFile(fileDescreption(filePath,fileName));  }  


原程序放在“Server”文件夹下,里面除了原程序外还有“data”文件夹,“data”文件夹下有文件“test”,

运行结果:打印出”test”文件中的内容。

0 0
原创粉丝点击