C++(MFC)得到文件夹路径,之后怎么遍历文件夹里面的文件(char*)保存

2025-04-14 19:10:12
推荐回答(3个)
回答1:

这个是删除文件的用法,找到文件和删除文件都差不多。用CFileFinder可以遍历。

void DelFiles(CString& strDirPath, CString strFileName, BOOL bDelAll)  
{  
    CFileFind FileFinder;  
    strDirPath  = strDirPath + _T("\\");  
    CString strFilePath = strDirPath + strFileName;  
  
    while (TRUE)  
    {  
        if (FileFinder.FindFile(strFilePath))  
        {  
            FileFinder.FindNextFile();  
            CString strDelFilePath  = FileFinder.GetFileName();  
            strDelFilePath = strDirPath + strDelFilePath;  
            DelDirectory(strDelFilePath);  
  
            if (!bDelAll)  
            {  
                break;  
            }  
        }  
        else  
        {  
            break;  
        }  
    }  
    FileFinder.Close();  
}

回答2:

//前面的#include等语句省略。
//成功返回TRUE,失败返回FALSE。
//只是在有文件的地方注释了,存储或显示方面可以自己做。
BOOL GetAllFile(LPCTSTR dirpath)
{
HANDLE h;
WIN32_FIND_DATA wfd;
TCHAR path[MAX_PATH];
BOOL more_files = TRUE;

_stprintf(path, _T("%s\\*.*"), dirpath);
h = FindFirstFile(dirpath, &wfd);
if(h == INVALID_HANDLE_VALUE)
return FALSE;

while(more_files)
{
if(_tcscmp(wfd.cFileName, _T(".")) == 0 || _tcscmp(wfd.cFileName, _T("..")) == 0)
{
//忽略 . 和 ..
}
else if((wfd.dwFileAttributes | FILE_ATTRIBUTE_DIRECTORY) != 0)
{
//处理子目录
TCHAR temp[MAX_PATH];
_stprintf(temp, _T("%s\\%s"), dirpath, wfd.cFileName);
if(!GetAllFile(temp))
{
FindClose(h);
return FALSE;
}
}
else
{
//这里就是文件,temp存放的就是全路径
TCHAR temp[MAX_PATH];
_stprintf(temp, _T("%s\\%s"), dirpath, wfd.cFileName);
}

more_files = FindNextFile(h, &wfd);
if(!more_files && GetLastError() != ERROR_NO_MORE_FILES)
{
FindClose(h);
return FALSE;
}
}

FindClose(h);
return TRUE;
}

这样调用
GetAllFile("C:\\temp");

回答3:

保存 在 想要的位置就行