日期:2014-05-18  浏览次数:21207 次

如何读取一个文件夹目录下的全部文件
如题
要读取一个文件夹中的所有文件,如果还有一层文件夹的也要进入到文件夹目录中进行文件的读取,直到读完为止!!

------解决方案--------------------
#include "StdAfx.h"

#include "SampleBase.h"

#include <windows.h>

#include <shlwapi.h>

#include <stack>

#include <string>

 

#ifdef UNICODE

# define tstring wstring

#else

# define tstring string

#endif

 

using namespace std;

 

void CLoadImageIssueSample::Run(HWND hwnd)

{

WIN32_FIND_DATA findFileData;

ZeroMemory(&findFileData, sizeof(WIN32_FIND_DATA));

TCHAR szCurDir[MAX_PATH];

 

::GetCurrentDirectory(MAX_PATH, szCurDir);

 

HANDLE handle = FindFirstFile(TEXT("Resources\\CLoadImageIssueSample\\*"), &findFileData);

stack<tstring> dirStack;

tstring baseDir(szCurDir);

baseDir += TEXT("\\");

baseDir += TEXT("Resources\\CLoadImageIssueSample");

while ( handle != INVALID_HANDLE_VALUE )

{

do 

{

tstring fileName(baseDir);

fileName += TEXT("\\");

fileName += findFileData.cFileName;

 

if ( (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 

FILE_ATTRIBUTE_DIRECTORY )

{

if ( StrCmp(findFileData.cFileName, TEXT(".")) == 0 ||

StrCmp(findFileData.cFileName, TEXT("..")) == 0 )

continue;

else

{

dirStack.push(fileName);

// 并不删除cFileName,到时一起释放

ZeroMemory(&findFileData, sizeof(WIN32_FIND_DATA));

}

}

else

{

if ( NULL == ::LoadImage(NULL, fileName.c_str(), 

IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE) )

{

LPVOID lpMsgBuf;

DWORD dw = GetLastError();

 

FormatMessage(

FORMAT_MESSAGE_ALLOCATE_BUFFER | 

FORMAT_MESSAGE_FROM_SYSTEM |

FORMAT_MESSAGE_IGNORE_INSERTS,

NULL,

dw,

MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),

(LPTSTR) &lpMsgBuf,

0, NULL );

 

MessageBox(NULL, (LPCTSTR)lpMsgBuf, TEXT("Error"), MB_OK); 

LocalFree(lpMsgBuf);

}

 

ZeroMemory(&findFileData, sizeof(WIN32_FIND_DATA));

}

} while ( FindNextFile(handle, &findFileData) != 0 );

 

FindClose(handle);

if ( !dirStack.empty() )

{

baseDir = dirStack.top();

tstring format = baseDir + TEXT("\\*");

handle = FindFirstFile(format.c_str(), &findFileData);

dirStack.pop();

}

}

}

------解决方案--------