先大体参考算法
关于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.net
这里面说与目标文件名“最符合”,可自由定义最符合的条件:相同、包含、通配符匹配之类均可以,大不了加个匹配算法code
#include
#include
#include
#include
#include
#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”,blog
运行结果:打印出”test”文件中的内容。字符串