如何用C读取一个文件夹的所有文件
如何用C读取文件夹/usr下的所有文件1AH7.pdb,2DRI.pdb,1C5A.pdb,...等.
还有个问题,如何将结果导出到result文件呢?
[解决办法]
Linux:
chdir("/usr");
system("ls *.pdb > pdbdump.txt");
Windows:
_chdir("/usr");
system("ls *.pdb > pdbdump.txt");
[解决办法]
想要统一处理某个文件夹下,某种文件,可以先用C++的容器将文件路径保存,然后逐个处理。
以下供参考:
//获取文件夹下子文件、文件夹std::vector<std::string> TFile::getsubpath(){ std::vector<std::string> subpath; std::string strfpname; subpath.clear(); intptr_t fcode; struct _finddata_t fdata; if (iffdir()) { fcode=_findfirst((fpath+"\\*").c_str(),&fdata); /*find first file;*/ strfpname=fdata.name; if ((strfpname!=".")&&(strfpname!="..")) { subpath.push_back(fpath+'\\'+strfpname); } /*find next file;*/ while(_findnext(fcode,&fdata)==0) { strfpname=fdata.name; if ((strfpname!=".")&&(strfpname!="..")) { subpath.push_back(fpath+'\\'+strfpname); } } _findclose(fcode); } return subpath;}//获取文件夹下,所有子文件std::vector<std::string> TFile::getsubfile(){ std::vector<std::string> subfile; subfile.clear(); listsub(subfile); return subfile;}//循环递归,找出子文件夹下子文件void TFile::listsub(std::vector<std::string>& subfile){ if (iffdir()) { std::vector<std::string> subpath=getsubpath(); std::vector<std::string>::iterator it_sub=subpath.begin(); while (it_sub<subpath.end()) { TFile subf((*it_sub)); subf.listsub(subfile); it_sub++; } } else subfile.push_back(fpath);}