用下面的代码,只能获取指定目录下的文件夹名,
如何获取指定目录下所有文件名,包括子目录文件名。。。
#include <string>
#include <io.h>
using namespace std;
//获取指定目录下的文件列表
/* strDir=D:\\t0506\\ */
BOOL getfilelist(CString strSourceDir, CString fileListPath)
{
//保存文件列表
CString strFileList = "";
//要查找的目录
strSourceDir = strSourceDir + "*.*";
_finddata_t file;
long longf;
if((longf = _findfirst(strSourceDir, &file))==-1l)
{
return FALSE;
}
else
{
string tempName;
while( _findnext(longf, &file ) == 0)
{
tempName = "";
tempName = file.name;
if (tempName == "..")
{
continue;
}
//保存文件名
strFileList.Insert(strFileList.GetLength(),file.name);
strFileList.Insert(strFileList.GetLength(), "\r\n");
}
}
_findclose(longf);
CFile txtFile; //文件列表写TXT文件
txtFile.Open(fileListPath,CFile::modeCreate|CFile::modeWrite);
txtFile.Write(strFileList,strFileList.GetLength());
txtFile.Close();
return TRUE;
}
//测试获取文件列表的函数
void CTrdDlg::OnButton1()
{
getfilelist("D:\\t0506\\", "list.txt");
}
10 个解决方案
#1
FileFinder.h
//////////////////////////////////////////////////////////////////////
// Implemented by Samuel Gonzalo
//
// You may freely use or modify this code
//////////////////////////////////////////////////////////////////////
//
// FileFinder.h: interface for the CFileFinder class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(__FILEFINDER_H__)
#define __FILEFINDER_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Path.h"
#include "GameFileFinder.h"
enum FindOptionsEnum
{
FIND_SIZE = (1L << 0),
FIND_DATEMODIFIED = (1L << 1),
FIND_DATECREATED = (1L << 2),
FIND_DATEACCESSED = (1L << 3),
FIND_ATTRIBUTES = (1L << 4),
FIND_TEXT = (1L << 5),
};
enum FileFinderProcCodes
{
FF_FOUND,
FF_DISCARDED,
FF_FOLDER,
FF_FINDTEXT,
};
class CFileFinder
{
public:
CFileFinder();
virtual ~CFileFinder();
class CFindOpts
{
public:
CFindOpts()
{
Reset();
}
~CFindOpts() {}
// Reset all values
void Reset()
{
sBaseFolder.Empty();
sFileMask = "*.*";
bSubfolders = FALSE;
nMinSize = nMaxSize = 0;
dwFileAttributes = 0;
dwOptionsFlags = 0;
tMinCreated = CTime::GetCurrentTime();
tMaxCreated = CTime::GetCurrentTime();
tMinModified = CTime::GetCurrentTime();
tMaxModified = CTime::GetCurrentTime();
tMinAccessed = CTime::GetCurrentTime();
tMaxAccessed = CTime::GetCurrentTime();
}
// Add normal files (FILE_ATTRIBUTE_ARCHIVE) to the search
void FindNormalFiles()
{
dwOptionsFlags |= FIND_ATTRIBUTES;
dwFileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
}
// Add all files to the search (hidden, read-only, ...) but no directories
void FindAllFiles()
{
dwOptionsFlags |= FIND_ATTRIBUTES;
dwFileAttributes |= FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_COMPRESSED |
FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY |
FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY;
}
// Add directories to the search
void FindDirectories()
{
dwOptionsFlags |= FIND_ATTRIBUTES;
dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
}
// Search for szText string in the files
void FindText(LPCTSTR szText)
{
dwOptionsFlags |= FIND_TEXT;
sFindText = szText;
}
CString sBaseFolder; // The starting folder for the search
CString sFileMask; // File mask (e.g.: "*.txt")
CString sFindText; // Text to find in the files
BOOL bSubfolders; // TRUE for recursive search
DWORD dwOptionsFlags; // Values in FindOptionsEnum
__int64 nMinSize; // File minimun size
__int64 nMaxSize; // File maximum file
CTime tMinCreated; // File oldest creation date
CTime tMaxCreated; // File newest creation date
CTime tMinModified; // File oldest modified date
CTime tMaxModified; // File newest modified date
CTime tMinAccessed; // File oldest accessed date
CTime tMaxAccessed; // File newest accessed date
DWORD dwFileAttributes; // like in WIN32_FIND_DATA
};
// Find files matching the mask under the base folder
int FindFiles(LPCTSTR szBaseFolder, LPCTSTR szFileMask, BOOL bSubFolders = FALSE);
// Find files matching the conditions stablished in the CFindOpts class parameter
int Find(CFileFinder::CFindOpts &opts);
// Return TRUE if the text szText was found in the file szFile
BOOL FindTextInFile(LPCTSTR szFile, LPCTSTR szText);
// Return the count of items found up to the moment
int GetFileCount();
// Return szPath file index in the list or -1 if it wasn't found
int FindPathItem(LPCTSTR szPath);
// Return a CPath object with the required file index path
CPath GetFilePath(int nIndex);
// Remove item at nIndex position
void RemoveAt(int nIndex);
// Remove all items from the list
void RemoveAll();
// Set the find method callback function
void SetCallback(FILEFINDERPROC pFileFinderProc, void *pCustomParam);
// Stop the search process started by a call to Find (or FindFiles)
void StopSearch();
// Return the current folder being searched
LPCTSTR GetSearchingFolder();
private:
CStringArray _aFilesFound;
bool _bStopSearch;
FILEFINDERPROC _pFileFinderProc;
void *_pCustomParam;
CString _sSearchingFolder;
};
#endif // !defined(__FILEFINDER_H__)
#2
FileFinder.cpp
CFileFinder _finder;
_finder.SetCallback();
nFileCounts += _finder.FindFiles();
//////////////////////////////////////////////////////////////////////
// Implemented by Samuel Gonzalo
//
// You may freely use or modify this code
//////////////////////////////////////////////////////////////////////
//
// FileFinder.cpp: implementation of the CFileFinder class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "FileFinder.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFileFinder::CFileFinder()
{
_bStopSearch = false;
_pFileFinderProc = NULL;
_pCustomParam = NULL;
}
CFileFinder::~CFileFinder()
{
}
int CFileFinder::FindFiles(LPCTSTR szBaseFolder, LPCTSTR szFileMask, BOOL bSubFolders)
{
CFindOpts opts;
opts.sBaseFolder = szBaseFolder;
opts.sFileMask = szFileMask;
opts.bSubfolders = bSubFolders;
// Get all files, but no directories
opts.FindAllFiles();
Find(opts);
return GetFileCount();
}
int CFileFinder::Find(CFileFinder::CFindOpts &opts)
{
CFileFind finder;
CString sFullMask;
CFindOpts subOpts;
BOOL bFound, bValidFile;
CTime timeFile;
_bStopSearch = false;
opts.sBaseFolder = CPath::AddBackSlash(opts.sBaseFolder);
// Find directories
if (opts.bSubfolders)
{
sFullMask = opts.sBaseFolder + CString("*.*");
bFound = finder.FindFile(sFullMask);
while ((bFound) && (!_bStopSearch))
{
bFound = finder.FindNextFile();
if ((finder.IsDirectory()) && (!finder.IsDots()))
{
subOpts = opts;
subOpts.sBaseFolder = opts.sBaseFolder + finder.GetFileName();
// Recursive call
Find(subOpts);
}
}
}
finder.Close();
_sSearchingFolder = opts.sBaseFolder;
// Call callback procedure
if (_pFileFinderProc != NULL)
_pFileFinderProc((char*)GetSearchingFolder(), NULL, FF_FOLDER, _pCustomParam);
sFullMask = opts.sBaseFolder + opts.sFileMask;
bFound = finder.FindFile(sFullMask);
while ((bFound) && (!_bStopSearch))
{
bFound = finder.FindNextFile();
if (!finder.IsDots())
{
// check constrains
bValidFile = TRUE;
if (opts.dwOptionsFlags & FIND_ATTRIBUTES)
{
bValidFile = finder.MatchesMask(opts.dwFileAttributes);
}
if (bValidFile && (opts.dwOptionsFlags & FIND_SIZE))
{
bValidFile = ((opts.nMinSize <= finder.GetLength()) &&
(opts.nMaxSize >= finder.GetLength()));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_DATEMODIFIED))
{
finder.GetLastWriteTime(timeFile);
bValidFile = ((timeFile >= opts.tMinModified) &&
(timeFile <= opts.tMaxModified));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_DATECREATED))
{
finder.GetCreationTime(timeFile);
bValidFile = ((timeFile >= opts.tMinCreated) &&
(timeFile <= opts.tMaxCreated));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_DATEACCESSED))
{
finder.GetLastAccessTime(timeFile);
bValidFile = ((timeFile >= opts.tMinAccessed) &&
(timeFile <= opts.tMaxAccessed));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_TEXT))
{
bValidFile = FindTextInFile(finder.GetFilePath(), opts.sFindText);
}
// Add file to list
if (bValidFile)
{
CString sName = finder.GetFilePath();
if (finder.IsDirectory()) sName += "\\";
_aFilesFound.Add(sName);
}
// Call callback procedure
if (_pFileFinderProc != NULL)
_pFileFinderProc(GetFilePath(GetFileCount() - 1).GetLocation().GetBuffer(GetFilePath(GetFileCount() - 1).GetLocation().GetLength())
, GetFilePath(GetFileCount() - 1).GetFileName().GetBuffer(GetFilePath(GetFileCount() - 1).GetFileName().GetLength())
, bValidFile ? FF_FOUND : FF_DISCARDED, _pCustomParam);
}
}
return GetFileCount();
}
BOOL CFileFinder::FindTextInFile(LPCTSTR szFile, LPCTSTR szText)
{
if ((szText == NULL) || (szText == "")) return FALSE;
CFile file;
if (!file.Open(szFile, CFile::modeRead)) return FALSE;
const UINT nCMinBufSize = 128;
CString sText;
CString sFindText(szText);
UINT nFindTextLen = sFindText.GetLength();
UINT nBufSize = 128;
UINT nReadSize;
UINT nCharRead;
LPSTR pTextBuf;
BOOL bTextFound;
int nLoopCount = 0;
if ((2 * nFindTextLen) > nCMinBufSize)
nBufSize = (2 * nFindTextLen);
nReadSize = nBufSize - nFindTextLen;
sFindText.MakeUpper();
do
{
pTextBuf = sText.GetBuffer(nBufSize);
if (pTextBuf[0] == 0x0)
memset(pTextBuf, ' ', nFindTextLen);
else
memcpy(pTextBuf, pTextBuf + (nBufSize - nFindTextLen), nFindTextLen);
nCharRead = file.Read(pTextBuf + nFindTextLen, nReadSize);
sText.ReleaseBuffer(nFindTextLen + nCharRead);
sText.Remove('\0');
sText.MakeUpper();
bTextFound = (sText.Find(sFindText) != -1);
// Call callback procedure
if (_pFileFinderProc != NULL)
{
nLoopCount++;
if (nLoopCount == 10)
{
nLoopCount = 0;
_pFileFinderProc(
GetFilePath(GetFileCount() - 1).GetLocation().GetBuffer(GetFilePath(GetFileCount() - 1).GetLocation().GetLength())
, GetFilePath(GetFileCount() - 1).GetFileName().GetBuffer(GetFilePath(GetFileCount() - 1).GetFileName().GetLength())
, FF_FINDTEXT, _pCustomParam);
}
}
}
while ((nCharRead == nReadSize) && !bTextFound);
file.Close();
return bTextFound;
}
int CFileFinder::GetFileCount()
{
return _aFilesFound.GetSize();
}
int CFileFinder::FindPathItem(LPCTSTR szPath)
{
bool bFound;
int nIndex;
for (nIndex = 0; nIndex < _aFilesFound.GetSize(); nIndex++)
{
bFound = (_aFilesFound[nIndex].CompareNoCase(szPath) == 0);
if (bFound) break;
}
return (bFound ? nIndex : -1);
}
CPath CFileFinder::GetFilePath(int nIndex)
{
if ((nIndex < 0) || (nIndex >= GetFileCount())) return "";
return _aFilesFound[nIndex];
}
LPCTSTR CFileFinder::GetSearchingFolder()
{
return _sSearchingFolder;
}
void CFileFinder::RemoveAt(int nIndex)
{
if ((nIndex < 0) || (nIndex >= GetFileCount())) return;
_aFilesFound.RemoveAt(nIndex);
}
void CFileFinder::RemoveAll()
{
if (GetFileCount() > 0) _aFilesFound.RemoveAll();
}
void CFileFinder::SetCallback(FILEFINDERPROC pFileFinderProc, void *pCustomParam)
{
_pFileFinderProc = pFileFinderProc;
_pCustomParam = pCustomParam;
}
void CFileFinder::StopSearch()
{
_bStopSearch = true;
}
CFileFinder _finder;
_finder.SetCallback();
nFileCounts += _finder.FindFiles();
#3
如果遍历所有目录文件的话,你用POS试试。
#4
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO; //操作文件
using System.Collections; //操作动态数组
namespace getFileList
{
public partial class Form1 : Form
{
//递归遍历指定目录下的所有文件,结果保存在Txt文件中
private ArrayList al = new ArrayList();
private int aaa = 0;
public Form1()
{
InitializeComponent();
}
//递归获取指定目录下的所有文件
private void GetAllDirList(string strBaseDir)
{
DirectoryInfo di = new DirectoryInfo(strBaseDir);
DirectoryInfo[] diA = di.GetDirectories();
if (aaa == 0)
{
FileInfo[] fis2 = di.GetFiles();
for (int i2 = 0; i2 < fis2.Length; i2++)
{
al.Add(fis2[i2].FullName);
}
}
for (int i = 0; i < diA.Length; i++)
{
aaa++;
al.Add(diA[i].FullName + "\t<文件夹>");
DirectoryInfo di1 = new DirectoryInfo(diA[i].FullName);
DirectoryInfo[] diA1 = di1.GetDirectories();
FileInfo[] fis1 = di1.GetFiles();
for (int ii = 0; ii < fis1.Length; ii++)
{
al.Add(fis1[ii].FullName);
}
GetAllDirList(diA[i].FullName);
}
}
//文件列表写入Txt文件
public void GetCurFile_List(string sourceFilePath, string destFilePath)
{
string str_path = sourceFilePath;
string dest_path = destFilePath;
string tmp = "";
int seq = -1;
al.Clear();
this.GetAllDirList(str_path);
if (File.Exists(dest_path))
{
File.Delete(dest_path);
}
StreamWriter sw = new StreamWriter(dest_path);
//序号+文件绝对路径
for (int i = 0; i < al.Count; i++)
{
seq = i + 1;
tmp = seq.ToString() + "\t" + al[i].ToString();
sw.WriteLine(tmp);
/*
tmp += seq.ToString();
tmp += "\t";
tmp += al[i].ToString();
tmp += "\r\n";
*/
}
//sw.WriteLine(tmp);
sw.Flush();
sw.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string source_Dir = "D:\\要搜索的根目录\\";
string dest_TxtPath = "D:\\文件列表.txt";
GetCurFile_List(source_Dir, dest_TxtPath);
MessageBox.Show("搜索结束");
}
}
}
#5
递归调用
#6
网上有现成的
百度下
百度下
#7
CFileFind类的FindFile/FindNextFile();
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
CString str = finder.GetFilePath();
TRACE(_T("%s\n"), (LPCTSTR)str);
if (finder.IsDirectory())
{
Recurse(str);
}
}
finder.Close();
}
void PrintDirs()
{
Recurse(_T("C:"));
}
#8
CFileFind类的FindFile/FindNextFile();
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
CString str = finder.GetFilePath();
TRACE(_T("%s\n"), (LPCTSTR)str);
if (finder.IsDirectory())
{
Recurse(str);
}
}
finder.Close();
}
void PrintDirs()
{
Recurse(_T("C:"));
}
#9
CFileFind类的FindFile/FindNextFile();
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
CString str = finder.GetFilePath();
TRACE(_T("%s\n"), (LPCTSTR)str);
if (finder.IsDirectory())
{
Recurse(str);
}
}
finder.Close();
}
void PrintDirs()
{
Recurse(_T("C:"));
}
#10
用 FSO
我有个 VB 的例子:
Option Explicit
Public Sub 遍历文件夹和文件(sFolder As String)
Dim fs As Object
On Error Resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
File_Folder_List (fs.GetFolder(sFolder))
Set fs = Nothing
End Sub
Private Sub File_Folder_List(df As Object)
'循环处理文件集合
Dim objFile As Object, objSubFolder As Object
'文件集合
For Each objFile In df.Files
'
'
'文件处理过程
'
'
Next objFile
Set objFile = Nothing
'文件夹集合
For Each objSubFolder In df.SubFolders
'
'
'文件夹处理过程
'
'
File_Folder_List objSubFolder '递归循环处理文件夹
Next objSubFolder
Set objSubFolder = Nothing
End Sub
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/z_wenqian/archive/2011/04/28/6368870.aspx
我有个 VB 的例子:
Option Explicit
Public Sub 遍历文件夹和文件(sFolder As String)
Dim fs As Object
On Error Resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
File_Folder_List (fs.GetFolder(sFolder))
Set fs = Nothing
End Sub
Private Sub File_Folder_List(df As Object)
'循环处理文件集合
Dim objFile As Object, objSubFolder As Object
'文件集合
For Each objFile In df.Files
'
'
'文件处理过程
'
'
Next objFile
Set objFile = Nothing
'文件夹集合
For Each objSubFolder In df.SubFolders
'
'
'文件夹处理过程
'
'
File_Folder_List objSubFolder '递归循环处理文件夹
Next objSubFolder
Set objSubFolder = Nothing
End Sub
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/z_wenqian/archive/2011/04/28/6368870.aspx
#1
FileFinder.h
//////////////////////////////////////////////////////////////////////
// Implemented by Samuel Gonzalo
//
// You may freely use or modify this code
//////////////////////////////////////////////////////////////////////
//
// FileFinder.h: interface for the CFileFinder class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(__FILEFINDER_H__)
#define __FILEFINDER_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Path.h"
#include "GameFileFinder.h"
enum FindOptionsEnum
{
FIND_SIZE = (1L << 0),
FIND_DATEMODIFIED = (1L << 1),
FIND_DATECREATED = (1L << 2),
FIND_DATEACCESSED = (1L << 3),
FIND_ATTRIBUTES = (1L << 4),
FIND_TEXT = (1L << 5),
};
enum FileFinderProcCodes
{
FF_FOUND,
FF_DISCARDED,
FF_FOLDER,
FF_FINDTEXT,
};
class CFileFinder
{
public:
CFileFinder();
virtual ~CFileFinder();
class CFindOpts
{
public:
CFindOpts()
{
Reset();
}
~CFindOpts() {}
// Reset all values
void Reset()
{
sBaseFolder.Empty();
sFileMask = "*.*";
bSubfolders = FALSE;
nMinSize = nMaxSize = 0;
dwFileAttributes = 0;
dwOptionsFlags = 0;
tMinCreated = CTime::GetCurrentTime();
tMaxCreated = CTime::GetCurrentTime();
tMinModified = CTime::GetCurrentTime();
tMaxModified = CTime::GetCurrentTime();
tMinAccessed = CTime::GetCurrentTime();
tMaxAccessed = CTime::GetCurrentTime();
}
// Add normal files (FILE_ATTRIBUTE_ARCHIVE) to the search
void FindNormalFiles()
{
dwOptionsFlags |= FIND_ATTRIBUTES;
dwFileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
}
// Add all files to the search (hidden, read-only, ...) but no directories
void FindAllFiles()
{
dwOptionsFlags |= FIND_ATTRIBUTES;
dwFileAttributes |= FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_COMPRESSED |
FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY |
FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY;
}
// Add directories to the search
void FindDirectories()
{
dwOptionsFlags |= FIND_ATTRIBUTES;
dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
}
// Search for szText string in the files
void FindText(LPCTSTR szText)
{
dwOptionsFlags |= FIND_TEXT;
sFindText = szText;
}
CString sBaseFolder; // The starting folder for the search
CString sFileMask; // File mask (e.g.: "*.txt")
CString sFindText; // Text to find in the files
BOOL bSubfolders; // TRUE for recursive search
DWORD dwOptionsFlags; // Values in FindOptionsEnum
__int64 nMinSize; // File minimun size
__int64 nMaxSize; // File maximum file
CTime tMinCreated; // File oldest creation date
CTime tMaxCreated; // File newest creation date
CTime tMinModified; // File oldest modified date
CTime tMaxModified; // File newest modified date
CTime tMinAccessed; // File oldest accessed date
CTime tMaxAccessed; // File newest accessed date
DWORD dwFileAttributes; // like in WIN32_FIND_DATA
};
// Find files matching the mask under the base folder
int FindFiles(LPCTSTR szBaseFolder, LPCTSTR szFileMask, BOOL bSubFolders = FALSE);
// Find files matching the conditions stablished in the CFindOpts class parameter
int Find(CFileFinder::CFindOpts &opts);
// Return TRUE if the text szText was found in the file szFile
BOOL FindTextInFile(LPCTSTR szFile, LPCTSTR szText);
// Return the count of items found up to the moment
int GetFileCount();
// Return szPath file index in the list or -1 if it wasn't found
int FindPathItem(LPCTSTR szPath);
// Return a CPath object with the required file index path
CPath GetFilePath(int nIndex);
// Remove item at nIndex position
void RemoveAt(int nIndex);
// Remove all items from the list
void RemoveAll();
// Set the find method callback function
void SetCallback(FILEFINDERPROC pFileFinderProc, void *pCustomParam);
// Stop the search process started by a call to Find (or FindFiles)
void StopSearch();
// Return the current folder being searched
LPCTSTR GetSearchingFolder();
private:
CStringArray _aFilesFound;
bool _bStopSearch;
FILEFINDERPROC _pFileFinderProc;
void *_pCustomParam;
CString _sSearchingFolder;
};
#endif // !defined(__FILEFINDER_H__)
#2
FileFinder.cpp
CFileFinder _finder;
_finder.SetCallback();
nFileCounts += _finder.FindFiles();
//////////////////////////////////////////////////////////////////////
// Implemented by Samuel Gonzalo
//
// You may freely use or modify this code
//////////////////////////////////////////////////////////////////////
//
// FileFinder.cpp: implementation of the CFileFinder class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "FileFinder.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFileFinder::CFileFinder()
{
_bStopSearch = false;
_pFileFinderProc = NULL;
_pCustomParam = NULL;
}
CFileFinder::~CFileFinder()
{
}
int CFileFinder::FindFiles(LPCTSTR szBaseFolder, LPCTSTR szFileMask, BOOL bSubFolders)
{
CFindOpts opts;
opts.sBaseFolder = szBaseFolder;
opts.sFileMask = szFileMask;
opts.bSubfolders = bSubFolders;
// Get all files, but no directories
opts.FindAllFiles();
Find(opts);
return GetFileCount();
}
int CFileFinder::Find(CFileFinder::CFindOpts &opts)
{
CFileFind finder;
CString sFullMask;
CFindOpts subOpts;
BOOL bFound, bValidFile;
CTime timeFile;
_bStopSearch = false;
opts.sBaseFolder = CPath::AddBackSlash(opts.sBaseFolder);
// Find directories
if (opts.bSubfolders)
{
sFullMask = opts.sBaseFolder + CString("*.*");
bFound = finder.FindFile(sFullMask);
while ((bFound) && (!_bStopSearch))
{
bFound = finder.FindNextFile();
if ((finder.IsDirectory()) && (!finder.IsDots()))
{
subOpts = opts;
subOpts.sBaseFolder = opts.sBaseFolder + finder.GetFileName();
// Recursive call
Find(subOpts);
}
}
}
finder.Close();
_sSearchingFolder = opts.sBaseFolder;
// Call callback procedure
if (_pFileFinderProc != NULL)
_pFileFinderProc((char*)GetSearchingFolder(), NULL, FF_FOLDER, _pCustomParam);
sFullMask = opts.sBaseFolder + opts.sFileMask;
bFound = finder.FindFile(sFullMask);
while ((bFound) && (!_bStopSearch))
{
bFound = finder.FindNextFile();
if (!finder.IsDots())
{
// check constrains
bValidFile = TRUE;
if (opts.dwOptionsFlags & FIND_ATTRIBUTES)
{
bValidFile = finder.MatchesMask(opts.dwFileAttributes);
}
if (bValidFile && (opts.dwOptionsFlags & FIND_SIZE))
{
bValidFile = ((opts.nMinSize <= finder.GetLength()) &&
(opts.nMaxSize >= finder.GetLength()));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_DATEMODIFIED))
{
finder.GetLastWriteTime(timeFile);
bValidFile = ((timeFile >= opts.tMinModified) &&
(timeFile <= opts.tMaxModified));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_DATECREATED))
{
finder.GetCreationTime(timeFile);
bValidFile = ((timeFile >= opts.tMinCreated) &&
(timeFile <= opts.tMaxCreated));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_DATEACCESSED))
{
finder.GetLastAccessTime(timeFile);
bValidFile = ((timeFile >= opts.tMinAccessed) &&
(timeFile <= opts.tMaxAccessed));
}
if (bValidFile && (opts.dwOptionsFlags & FIND_TEXT))
{
bValidFile = FindTextInFile(finder.GetFilePath(), opts.sFindText);
}
// Add file to list
if (bValidFile)
{
CString sName = finder.GetFilePath();
if (finder.IsDirectory()) sName += "\\";
_aFilesFound.Add(sName);
}
// Call callback procedure
if (_pFileFinderProc != NULL)
_pFileFinderProc(GetFilePath(GetFileCount() - 1).GetLocation().GetBuffer(GetFilePath(GetFileCount() - 1).GetLocation().GetLength())
, GetFilePath(GetFileCount() - 1).GetFileName().GetBuffer(GetFilePath(GetFileCount() - 1).GetFileName().GetLength())
, bValidFile ? FF_FOUND : FF_DISCARDED, _pCustomParam);
}
}
return GetFileCount();
}
BOOL CFileFinder::FindTextInFile(LPCTSTR szFile, LPCTSTR szText)
{
if ((szText == NULL) || (szText == "")) return FALSE;
CFile file;
if (!file.Open(szFile, CFile::modeRead)) return FALSE;
const UINT nCMinBufSize = 128;
CString sText;
CString sFindText(szText);
UINT nFindTextLen = sFindText.GetLength();
UINT nBufSize = 128;
UINT nReadSize;
UINT nCharRead;
LPSTR pTextBuf;
BOOL bTextFound;
int nLoopCount = 0;
if ((2 * nFindTextLen) > nCMinBufSize)
nBufSize = (2 * nFindTextLen);
nReadSize = nBufSize - nFindTextLen;
sFindText.MakeUpper();
do
{
pTextBuf = sText.GetBuffer(nBufSize);
if (pTextBuf[0] == 0x0)
memset(pTextBuf, ' ', nFindTextLen);
else
memcpy(pTextBuf, pTextBuf + (nBufSize - nFindTextLen), nFindTextLen);
nCharRead = file.Read(pTextBuf + nFindTextLen, nReadSize);
sText.ReleaseBuffer(nFindTextLen + nCharRead);
sText.Remove('\0');
sText.MakeUpper();
bTextFound = (sText.Find(sFindText) != -1);
// Call callback procedure
if (_pFileFinderProc != NULL)
{
nLoopCount++;
if (nLoopCount == 10)
{
nLoopCount = 0;
_pFileFinderProc(
GetFilePath(GetFileCount() - 1).GetLocation().GetBuffer(GetFilePath(GetFileCount() - 1).GetLocation().GetLength())
, GetFilePath(GetFileCount() - 1).GetFileName().GetBuffer(GetFilePath(GetFileCount() - 1).GetFileName().GetLength())
, FF_FINDTEXT, _pCustomParam);
}
}
}
while ((nCharRead == nReadSize) && !bTextFound);
file.Close();
return bTextFound;
}
int CFileFinder::GetFileCount()
{
return _aFilesFound.GetSize();
}
int CFileFinder::FindPathItem(LPCTSTR szPath)
{
bool bFound;
int nIndex;
for (nIndex = 0; nIndex < _aFilesFound.GetSize(); nIndex++)
{
bFound = (_aFilesFound[nIndex].CompareNoCase(szPath) == 0);
if (bFound) break;
}
return (bFound ? nIndex : -1);
}
CPath CFileFinder::GetFilePath(int nIndex)
{
if ((nIndex < 0) || (nIndex >= GetFileCount())) return "";
return _aFilesFound[nIndex];
}
LPCTSTR CFileFinder::GetSearchingFolder()
{
return _sSearchingFolder;
}
void CFileFinder::RemoveAt(int nIndex)
{
if ((nIndex < 0) || (nIndex >= GetFileCount())) return;
_aFilesFound.RemoveAt(nIndex);
}
void CFileFinder::RemoveAll()
{
if (GetFileCount() > 0) _aFilesFound.RemoveAll();
}
void CFileFinder::SetCallback(FILEFINDERPROC pFileFinderProc, void *pCustomParam)
{
_pFileFinderProc = pFileFinderProc;
_pCustomParam = pCustomParam;
}
void CFileFinder::StopSearch()
{
_bStopSearch = true;
}
CFileFinder _finder;
_finder.SetCallback();
nFileCounts += _finder.FindFiles();
#3
如果遍历所有目录文件的话,你用POS试试。
#4
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO; //操作文件
using System.Collections; //操作动态数组
namespace getFileList
{
public partial class Form1 : Form
{
//递归遍历指定目录下的所有文件,结果保存在Txt文件中
private ArrayList al = new ArrayList();
private int aaa = 0;
public Form1()
{
InitializeComponent();
}
//递归获取指定目录下的所有文件
private void GetAllDirList(string strBaseDir)
{
DirectoryInfo di = new DirectoryInfo(strBaseDir);
DirectoryInfo[] diA = di.GetDirectories();
if (aaa == 0)
{
FileInfo[] fis2 = di.GetFiles();
for (int i2 = 0; i2 < fis2.Length; i2++)
{
al.Add(fis2[i2].FullName);
}
}
for (int i = 0; i < diA.Length; i++)
{
aaa++;
al.Add(diA[i].FullName + "\t<文件夹>");
DirectoryInfo di1 = new DirectoryInfo(diA[i].FullName);
DirectoryInfo[] diA1 = di1.GetDirectories();
FileInfo[] fis1 = di1.GetFiles();
for (int ii = 0; ii < fis1.Length; ii++)
{
al.Add(fis1[ii].FullName);
}
GetAllDirList(diA[i].FullName);
}
}
//文件列表写入Txt文件
public void GetCurFile_List(string sourceFilePath, string destFilePath)
{
string str_path = sourceFilePath;
string dest_path = destFilePath;
string tmp = "";
int seq = -1;
al.Clear();
this.GetAllDirList(str_path);
if (File.Exists(dest_path))
{
File.Delete(dest_path);
}
StreamWriter sw = new StreamWriter(dest_path);
//序号+文件绝对路径
for (int i = 0; i < al.Count; i++)
{
seq = i + 1;
tmp = seq.ToString() + "\t" + al[i].ToString();
sw.WriteLine(tmp);
/*
tmp += seq.ToString();
tmp += "\t";
tmp += al[i].ToString();
tmp += "\r\n";
*/
}
//sw.WriteLine(tmp);
sw.Flush();
sw.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string source_Dir = "D:\\要搜索的根目录\\";
string dest_TxtPath = "D:\\文件列表.txt";
GetCurFile_List(source_Dir, dest_TxtPath);
MessageBox.Show("搜索结束");
}
}
}
#5
递归调用
#6
网上有现成的
百度下
百度下
#7
CFileFind类的FindFile/FindNextFile();
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
CString str = finder.GetFilePath();
TRACE(_T("%s\n"), (LPCTSTR)str);
if (finder.IsDirectory())
{
Recurse(str);
}
}
finder.Close();
}
void PrintDirs()
{
Recurse(_T("C:"));
}
#8
CFileFind类的FindFile/FindNextFile();
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
CString str = finder.GetFilePath();
TRACE(_T("%s\n"), (LPCTSTR)str);
if (finder.IsDirectory())
{
Recurse(str);
}
}
finder.Close();
}
void PrintDirs()
{
Recurse(_T("C:"));
}
#9
CFileFind类的FindFile/FindNextFile();
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
CString str = finder.GetFilePath();
TRACE(_T("%s\n"), (LPCTSTR)str);
if (finder.IsDirectory())
{
Recurse(str);
}
}
finder.Close();
}
void PrintDirs()
{
Recurse(_T("C:"));
}
#10
用 FSO
我有个 VB 的例子:
Option Explicit
Public Sub 遍历文件夹和文件(sFolder As String)
Dim fs As Object
On Error Resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
File_Folder_List (fs.GetFolder(sFolder))
Set fs = Nothing
End Sub
Private Sub File_Folder_List(df As Object)
'循环处理文件集合
Dim objFile As Object, objSubFolder As Object
'文件集合
For Each objFile In df.Files
'
'
'文件处理过程
'
'
Next objFile
Set objFile = Nothing
'文件夹集合
For Each objSubFolder In df.SubFolders
'
'
'文件夹处理过程
'
'
File_Folder_List objSubFolder '递归循环处理文件夹
Next objSubFolder
Set objSubFolder = Nothing
End Sub
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/z_wenqian/archive/2011/04/28/6368870.aspx
我有个 VB 的例子:
Option Explicit
Public Sub 遍历文件夹和文件(sFolder As String)
Dim fs As Object
On Error Resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
File_Folder_List (fs.GetFolder(sFolder))
Set fs = Nothing
End Sub
Private Sub File_Folder_List(df As Object)
'循环处理文件集合
Dim objFile As Object, objSubFolder As Object
'文件集合
For Each objFile In df.Files
'
'
'文件处理过程
'
'
Next objFile
Set objFile = Nothing
'文件夹集合
For Each objSubFolder In df.SubFolders
'
'
'文件夹处理过程
'
'
File_Folder_List objSubFolder '递归循环处理文件夹
Next objSubFolder
Set objSubFolder = Nothing
End Sub
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/z_wenqian/archive/2011/04/28/6368870.aspx