因为项目需要,要把服务器上的一个目录转化为一个超级简单的XML文件,然后下载到客户端后,显示到树控件上,希望这样能够提高客户端显示目录的速度。原来的设计是每次打开目录都要连接服务器去读。上次已经完成了XML文件的解析,这次完成XML的生成。生成XML使用了Win32中很经典的查找文件的函数:FindFirstFile和FindNextFile。代码中还使用了SetCurrentDirectory和GetCurrentDirectory来设置文件的查找路径,减少了字符串处理。
要使用下面的代码,只需要这样调用即可:
SetCurrentDirectory(_T("D://Test"));
TraverseDirectory(_T("D://Test"));
/* Recursively traverse a directory and its subdirectories. */
BOOL TraverseDirectory(LPCTSTR lpszDirectory)
{
HANDLE SearchHandle;
WIN32_FIND_DATA FindData;
TCHAR CurrPath[MAX_PATH + 1];
static int tabCnt = 0;
return FALSE;
strPath += _T ("//");
strPath += _T ("*.*");
SearchHandle = FindFirstFile(strPath, &FindData);
if (SearchHandle == INVALID_HANDLE_VALUE) {
return FALSE;
}
/* Scan the directory and its subdirectories. */
do {
if (strcmp(FindData.cFileName, ".") == 0 || strcmp(FindData.cFileName, "..") == 0)
continue;
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
++tabCnt;
for (int i = 0; i != tabCnt; ++i)
out << ' ';
int idx = strPath.ReverseFind('//');
CString strChildPath = CString(strPath, idx + 1);
strChildPath += FindData.cFileName;
SetCurrentDirectory(strChildPath);
BOOL TraverseDirectory(LPCTSTR lpszDirectory)
{
HANDLE SearchHandle;
WIN32_FIND_DATA FindData;
TCHAR CurrPath[MAX_PATH + 1];
static int tabCnt = 0;
if (!lpszDirectory)
return FALSE;
out << "<DirectoryList Name="" << lpszDirectory << "">" << endl;
GetCurrentDirectory (MAX_PATH, CurrPath);
CString strPath(CurrPath);
strPath += _T ("//");
strPath += _T ("*.*");
/* Open up the directory search handle and get the first file name to satisfy the path name. */
SearchHandle = FindFirstFile(strPath, &FindData);
if (SearchHandle == INVALID_HANDLE_VALUE) {
return FALSE;
}
/* Scan the directory and its subdirectories. */
do {
if (strcmp(FindData.cFileName, ".") == 0 || strcmp(FindData.cFileName, "..") == 0)
continue;
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
++tabCnt;
for (int i = 0; i != tabCnt; ++i)
out << ' ';
int idx = strPath.ReverseFind('//');
CString strChildPath = CString(strPath, idx + 1);
strChildPath += FindData.cFileName;
SetCurrentDirectory(strChildPath);
/* Traverse the subdirectory recursively. */
TraverseDirectory(FindData.cFileName);
SetCurrentDirectory(_T(".."));
}
/* Get the next file or directory name. */
} while (FindNextFile(SearchHandle, &FindData));
FindClose(SearchHandle);
for (int i = 0; i != tabCnt; ++i)
out << ' ';
out << "</DirectoryList>" << endl;
--tabCnt;
}
TraverseDirectory(FindData.cFileName);
SetCurrentDirectory(_T(".."));
}
/* Get the next file or directory name. */
} while (FindNextFile(SearchHandle, &FindData));
FindClose(SearchHandle);
for (int i = 0; i != tabCnt; ++i)
out << ' ';
out << "</DirectoryList>" << endl;
--tabCnt;
return TRUE;
}