怎样读取一个文件夹下的头文件名,并整理出一个新的头文件

来源:互联网 发布:mac os x能玩剑网三吗? 编辑:程序博客网 时间:2024/05/01 12:54

相信大家在写头文件的时候会遇到这种情况,在一个cpp文件中要加入好多头文件,如下图:


如果我们像加普通头文件一样,一个个加入的话会一直复制粘贴非常麻烦,尤其是当不只一个cpp文件需要用的时候,如下图:


那么通常的办法是做出来一个总的头文件,然后加入这个总头文件就行了,如下图:

cpp文件中之直接声明 #include"AllHead.h" 就可以把所有头文件都加入了

但是写这样一个头文件还是需要很多粘贴和复制,于是写了以下代码,可以把一个目录下的文件名读取出来,并整理成一个总的头文件

代码如下:

#include<io.h>#include<fstream>#include<string>#include<vector>using namespace std;void getAllFiles( string path, vector<string>& files)  {  //文件句柄  long   hFile   =   0;  //文件信息  struct _finddata_t fileinfo;  string p;  if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) !=  -1)  {  do  {   if((fileinfo.attrib &  _A_SUBDIR))  {  if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)  {files.push_back(p.assign(path).append("\\").append(fileinfo.name) );getAllFiles( p.assign(path).append("\\").append(fileinfo.name), files ); }}  else  {  files.push_back(p.assign(path).append("\\").append(fileinfo.name) );  }  }while(_findnext(hFile, &fileinfo)  == 0);  _findclose(hFile); } }  //你要读取的头文件路径在哪儿#define CATALOG "E:\\2 C#\\tpc_e_driver\\tpc_e_driver\\inc"//最后结果的存储地点在哪儿#define SAVEFILE "AllHead.h"int main(){char * filePath = CATALOG; vector<string> files;  char * distAll = SAVEFILE ;getAllFiles(filePath, files);//该步骤的目的是去掉前面的目录for(vector<string> ::iterator it=files.begin();it!=files.end();it++){//0到38替换成#include" 因为"E:\\2 C#\\tpc_e_driver\\tpc_e_driver\\inc"的长度是0到38(*it).replace(0,38,"  #include\"./inc/");(*it)+="\"";//后面加上右侧的"}ofstream ofn(distAll);int size = files.size();//加上宏定义ofn<<"#ifndef ALL"<<endl;ofn<<"#define ALL"<<endl;for (int i = 0;i<size;i++)  {  ofn<<files[i]<<endl;  }ofn<<"#endif"<<endl;ofn.close();return 0;}
从#define的宏定义开始的注释处,都是需要用户自己定义修改的,请大家根据自己的需求来修改,最后生成的AllHead.h的文件在工程文件的根目录下面

如下图:




0 0
原创粉丝点击