关于判断目录存在、获取路径、遍历目录下文件

判断一目录是否存在,若不存在则创建该目录

#include <fstream>
wstring strPath("C:\Temp\log");
fstream _file;
        _file.open(strPath, ios::in);
        if (!_file)
            CreateDirectory(strPath.c_str(), NULL);

获取可执行文件的当前目录

1 #include <wchar.h>
2 
3 TCHAR szFilePath[MAX_PATH + 1];
4     GetModuleFileName(NULL, szFilePath, MAX_PATH);
5     (wcsrchr(szFilePath, '\'))[1] = 0;//删除文件名,只获得路径

遍历某目录下所有文件

 1 // 遍历文件夹,获取文件信息
 2 void TravelFolder(CString strDir)
 3 {
 4     // 文件当前目录
 5     TCHAR Buffer[MAX_PATH];
 6     DWORD dwRet = GetCurrentDirectory(MAX_PATH, Buffer);
 7     CString strCurrent(Buffer);
 8 
 9     CFileFind filefind;                                         //声明CFileFind类型变量
10 
11     CString strWildpath = strDir + _T("\*.*");     //所有文件都列出。
12 
13     if(filefind.FindFile(strWildpath, 0))                    //开始检索文件
14     {
15         BOOL bRet = TRUE;
16 
17         while(bRet)
18         {
19             bRet = filefind.FindNextFile();                 //枚举一个文件            
20 
21             if(filefind.IsDots())                                 //如果是. 或 .. 做下一个
22             {
23                 continue;
24             }
25 
26             // 文件名 begin
27             CString strFileName = filefind.GetFileName();
28             // 文件名 end
29 
30             // 文件修改时间 begin
31             FILETIME   filetime;
32             FILETIME   localtime;
33             SYSTEMTIME systemtime;
34             filefind.GetLastWriteTime(&filetime);
35 
36             FileTimeToLocalFileTime(&filetime, &localtime); //换成本地时间
37 
38             FileTimeToSystemTime(&localtime, &systemtime);  //换成系统时间格式
39 
40             CString strTime = _T("");
41             strTime.Format(_T("%04d%02d%02d%02d%02d%02d"),
42                 systemtime.wYear, systemtime.wMonth, systemtime.wDay,
43                 systemtime.wHour, systemtime.wMinute, systemtime.wSecond);
44             // 文件修改时间 end            
45 
46             if(!filefind.IsDirectory())                          //不是子目录,把文件名打印出来
47             {
48                 CString strWrite = _T("");
49                 strWrite += strFileName;
50                 strWrite += _T("	");
51                 strWrite += strTime;
52                 strWrite +=  + _T("
");
53                 TRACE(strWrite);
54             }
55             else                                                   //如果是子目录,递归调用该函数
56             {
57                 CString strNewDir = strDir + CString(_T("\")) + filefind.GetFileName();
58 
59                 TravelFolder(strNewDir);//递归调用该函数打印子目录里的文件
60             }
61         }
62 
63         filefind.Close();
64     }
65 }
原文地址:https://www.cnblogs.com/Uthinker/p/5765579.html