VC++中目录操作

目录

在VC++中利用Windows SDK操控目录。

程序中需要用到之前一篇文章中定义的字符串转换函数,具体函数见《wstring 与 string 的转换
获取当前目录
GetCurrentDirectory()函数
[cpp]
std::string getCurrentDirectory( void )
{
WCHAR Buffer[BUFSIZE];
DWORD dwRet;
dwRet = GetCurrentDirectory(BUFSIZE, Buffer);
if( dwRet == 0 )
{
printf(“GetCurrentDirectory failed (%d)\n”, GetLastError());
return string();
}
if(dwRet > BUFSIZE)
{
printf(“Buffer too small; need %d characters\n”, dwRet);
return string();
}
wstring wstr(Buffer);
return StringManager::wstring2string(wstr);
}
[/cpp]
获取目录下的文件信息
FindFirstFile()、FindNextFile()等函数读取文件信息。
遍历目录下的所有文件和子目录
FindFirstFile()、FindNextFile()两个函数结合实现。
[cpp]
int listFilesInDirectory( const std::string & fileDir, const std::string & filter, std::vectorstd::string & fileList )
{
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError=0;
fileList.clear();
wstring wcdir = string2wstring(fileDir + “\” + filter);
hFind = FindFirstFile(wcdir.c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
_tprintf(TEXT(“FindFirstFile\n”));
return dwError;
}
// List all the files in the directory with some info about them.
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// dir
}
else
{
// file
string strFileName = wchar2string(ffd.cFileName);
fileList.push_back(strFileName);
}
}
while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
_tprintf(TEXT(“FindFirstFile\n”));
}
FindClose(hFind);
return dwError;
}
[/cpp]