c++遍历某个路径下的所有文件(比如txt)
hi,如题,
1.我想在windows下实现(我在linux上实现了,但是用到了一个库,windows下没有);
2.我不想依赖VS之类的,感觉他们也是有些自己独特的库,因为我现在用codeblocks;
3.之前有个人用C++调用cmd的部分命令,一句话就把路径下的所有文件名称写到开一个txt文件,然后通过读取该txt文件来遍历这些文件,我实现了,但觉得还不是我想要的。
用VS实现可以,但保证我在codeblocks下不用VS的编译器也能实现就行了,谢谢啦!!!
[解决办法]
给一段以前写的代码,供参考:
// 遍历给定目录下所有子目录,查找*.txt,放入CStringArray中
void CTestMADlg::getFolderDayFile(CString pathStr, CStringArray& arrStrFile)
{
CString myDataPath,fdPath;
myDataPath=pathStr + "\\*.*";
CString strTmp;
CFileFind find;
BOOL bf = find.FindFile(myDataPath);
while(bf)
{
bf = find.FindNextFile();
if(!find.IsDots())
{
fdPath=find.GetFilePath();
if (find.IsDirectory())
{
//如果是文件夹,递归,继续往下找
getFolderDayFile(fdPath, arrStrFile);
}
else
{
//如果是文件,判断是否是*.txt
strTmp=fdPath.Right(4);
strTmp.MakeLower();
if ( strTmp==".txt" )
arrStrFile.Add(fdPath);
}
}
}
find.Close();
}
谢谢,不过一看我感觉就是严重依赖MFC或者VS的。
能写个满足我1,2,3条要求的程序不?谢谢啦!
#include <stdio.h>
#include <io.h>
int main (void)
{
_finddata_t fileDir;
char* dir="d:\\temp\\*.*";
long lfDir;
if((lfDir = _findfirst(dir,&fileDir))==-1l)
printf("No file is found\n");
else{
printf("file list:\n");
do{
printf("%s\n",fileDir.name);
}while( _findnext( lfDir, &fileDir ) == 0 );
}
_findclose(lfDir);
return 0;
}