使用C++把文件夹目录信息转化为XML文件

因为项目需要,要把服务器上的一个目录转化为一个超级简单的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 ;     if (! lpszDirectory)         return  FALSE;     out << "<DirectoryList Name="" << lpszDirectory << "">" <<  endl;     GetCurrentDirectory (MAX_PATH, CurrPath);     CString strPath(CurrPath);     if (strPath.Right (1!= _T ("//" ))         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;     return  TRUE; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值