不知道用递归的方法行不行? 我觉得可以这样做:写一个遍历目录的函数BianLi(Folder)! BianLi(Folder) { pFile=GetFirstFileName(); While pFile<>nil { Compare pFile with the file you are searching; if Same Goto where you want; pFile=GetNextFileName(pFile); };
pFolder=GetFirstSubFolder(); While pFolder<>nil { BianLi(pFolder); pFolder=GetNextSubFolder(pFolder); };}我写的只是简单的递归算法,不是C++的语法,可能帮不了你的忙,只供你做点参考吧!
::FindNextFile
::FindClose
我觉得可以这样做:写一个遍历目录的函数BianLi(Folder)!
BianLi(Folder)
{
pFile=GetFirstFileName();
While pFile<>nil
{
Compare pFile with the file you are searching;
if Same Goto where you want;
pFile=GetNextFileName(pFile);
};
pFolder=GetFirstSubFolder();
While pFolder<>nil
{
BianLi(pFolder);
pFolder=GetNextSubFolder(pFolder);
};}我写的只是简单的递归算法,不是C++的语法,可能帮不了你的忙,只供你做点参考吧!
的所有文本文件合到我创建的一个文件中,你可以看看.
我写的是命令行的.
不过那是核心了.
下面是代码
/*用法: my <dir> <savefilename.txt> */
/*由于我用到CFile所以我把mfc.dll和它编译在一起了,所以个子比较大*/
/*关键在那个数组,这样不用递归就可以了*/
#include<afx.h>
#include<iostream.h>
#include <afxwin.h>//判断该文件是文本文件
BOOL IsTextFile(CString str)
{
if(str.GetAt(str.GetLength() - 1)=='t' && str.GetAt(str.GetLength() -2)=='x'
&& str.GetAt(str.GetLength() -3) =='t'&& str.GetAt(str.GetLength() -4) =='.')
return TRUE; else
return FALSE;
}
void Process(LPCTSTR dirname,LPCTSTR DestFileName)
{
CStringArray dirs;
CString searchname;
CFileFind find;
dirs.Add(dirname);
BOOL bRet; CFileException error;
CStdioFile DestFile;
if(!(DestFile.Open(DestFileName,CFile::modeWrite|CFile::modeCreate
|CFile::typeText,&error)))
{
TCHAR szError[1024];
error.GetErrorMessage(szError, 1024);
cout << "Couldn't Create Destfile: ";
cout << szError;
exit(1);
}
while(dirs.GetSize()>0)
{
searchname = dirs[0] +"\\*.*";
dirs.RemoveAt(0);
bRet = find.FindFile (searchname);
if(!bRet)continue;
do{
bRet = find.FindNextFile (); if(find.IsDots ())
{
continue;
} if(find.IsDirectory())
{
dirs.Add (find.GetFilePath());
continue;
}
else{//防止自己写向自己
if(find.GetFileName() != DestFileName)
{
if(IsTextFile(find.GetFileName()))
{
CFile SourceFile;
if(!SourceFile.Open(find.GetFilePath(),CFile::modeRead,&error))
{
TCHAR szError[1024];
error.GetErrorMessage(szError, 1024);
cout << "Couldn't open source file ";
cout << szError;
exit(1);
}//if DWORD dwRead;
BYTE buffer[4096];
//read data do
{
dwRead = SourceFile.Read(buffer,4096);
DestFile.Write(buffer,dwRead);
}while(dwRead >0);//按块为4k写文件
DestFile.WriteString("\n");//每个文本文件间加换行符号 SourceFile.Close();
}
}//if
continue;
}//else
}while(bRet);
}
find.Close();
DestFile.Close();
} int main(int argc,char* argv[])
{
//初始化mfc库 if (!AfxWinInit(GetModuleHandle(NULL), NULL, GetCommandLine(), 0))
{
cout << "panic: MFC could not initialize!" << endl;
return 1;
}//see msdn //出错处理程序
if(argc != 3)
{
cout<<"需要输入2个参数"<<endl;
cout<<"usage: my <directory> <filename>"<<endl;
cout<<"for example: my d:\\mybook myfile.txt 或者"<<endl
<<"my d:\\mybook c:\\myfoloder\\mybook"<<endl;
exit(1);
}
cout<<"如果您的文件夹下面子目录过多或者文件过多的话,可能需要一点时间"<<endl;
Process(argv[1],argv[2]);
cout<<"操作成功"<<endl;
cout<<"press enter to exit..."<<endl;
getchar();
}