如何遍历文件 - C++ Builder / Windows SDK/API
请教怎么样把一个文件夹下把所有某种类型的文件名全部遍历到List里面?
用到什么类?什么方法?
[解决办法]
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TSearchRec sr;
int iAttributes = 0;
StringGrid1->RowCount = 1;
iAttributes |= faReadOnly * CheckBox1->Checked;
iAttributes |= faHidden * CheckBox2->Checked;
iAttributes |= faSysFile * CheckBox3->Checked;
iAttributes |= faVolumeID * CheckBox4->Checked;
iAttributes |= faDirectory * CheckBox5->Checked;
iAttributes |= faArchive * CheckBox6->Checked;
iAttributes |= faAnyFile * CheckBox7->Checked;
StringGrid1->RowCount = 0;
if (FindFirst(Edit1->Text, iAttributes, sr) == 0)
{
do
{
if ((sr.Attr & iAttributes) == sr.Attr)
{
StringGrid1->RowCount = StringGrid1->RowCount + 1;
StringGrid1->Cells[1][StringGrid1->RowCount-1] = sr.Name;
StringGrid1->Cells[2][StringGrid1->RowCount-1] = IntToStr(sr.Size);
}
} while (FindNext(sr) == 0);
FindClose(sr);
}
}
[解决办法]
void test(String path, String file_kind) //path为文件夹路径 , file_kind为扩展名
{
TSearchRec sr;
if(FindFirst(path+"\\*.*",faAnyFile,sr)==0)
{
try
{
do
{
if(sr.Name == "." || sr.Name == "..")
continue;
if(sr.Attr == faDirectory) //如果是文件夹递归
test(path + "\\" + sr.Name);
else
{
String file_name = path + "\\" + sr.Name;
if(ExtractFileExt(file_name) == file_kind) //如果是文件则比较扩展名
{
//这里加入到list中
}
}
}
}
}
[解决办法]
void TForm1::test(String path, String file_kind) //path?ゅン?隔? , file_kind??W
{
TSearchRec sr;
if(FindFirst(path+"\\*.*",faAnyFile,sr)==0)
{
try
{
do
{
if(sr.Name == "." || sr.Name == "..")
continue;
if(sr.Attr == faDirectory)//如果是文件夹递归
test(path + "\\" + sr.Name, file_kind);
else
{
String file_name = path + "\\" + sr.Name;
if(ExtractFileExt(file_name) == file_kind)//如果是文件则比较扩展名
{
//;
}
}
}
while(FindNext(sr)==0);
FindClose(sr);
}
catch(Exception &e)
{
FindClose(sr);
}
}
}
调用方式test("C:\\", ".bmp");
[解决办法]
- C/C++ code
void CrnListFilesInDir(String strDir, TStrings *pList, String strFileExt){ WIN32_FIND_DATA wfd; String strFileName; if (strDir.LastDelimiter("\\") != strDir.Length()) strDir += "\\"; HANDLE hFind = ::FindFirstFile((strDir + TEXT("*.*")).c_str(), &wfd); if (INVALID_HANDLE_VALUE != hFind) { do { strFileName = String(wfd.cFileName); // 忽略.和.. if (SameText(strFileName, TEXT(".")) || SameText(strFileName, TEXT(".."))) continue; // 如果是子目录就进入子目录搜索 if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) CrnListFilesInDir(strDir + strFileName + TEXT("\\"), pList, strFileExt); // 判断扩展名 if (SameText(strFileExt, TEXT("*.*")) || SameText(ExtractFileExt(strFileName), strFileExt)) { pList->Add(strDir + strFileName); } } while (::FindNextFile(hFind, &wfd)); } ::FindClose(hFind);}//---------------------------------------void __fastcall TForm1::Button1Click(TObject *Sender){ // 列举C:\ccrun目录下所有的.bmp文件(包含子目录)并将结果显示在Memo中 CrnListFilesInDir(TEXT("C:\\ccrun"), Memo1->Lines, TEXT(".bmp")); // 列举C:\ccrun目录下所有的文件(包含子目录)并将结果显示在Memo中 //CrnListFilesInDir(TEXT("C:\\ccrun"), Memo1->Lines, TEXT("*.*"));}