首页 > 代码库 > MFC常用的字符串、文件、目录操作

MFC常用的字符串、文件、目录操作

因为经常写一些文件处理的MFC程序,反复写同样的程序很头疼,于是自己编写整理了一个类,可以直接使用。

分享给需要经常进行这些操作的朋友,代码非常简单,如果有疏漏之处,还请多多指教。

 

首先是头文件:

/* ******* StrDirFile.h ******************* 字符串、文件、目录操作函数声明 ********** *//* author: autumoon */#ifndef _STR_DIR_FILE_#define _STR_DIR_FILE_#pragma comment(linker,"/manifestdependency:\"type=‘win32‘ name=‘Microsoft.Windows.Common-Controls‘ version=‘6.0.0.0‘ processorArchitecture=‘x86‘ publicKeyToken=‘6595b64144ccf1df‘ language=‘*‘\"")#include <afxdlgs.h> //打开文件#include <ShlObj.h> //浏览文件夹class CStrDirFile{public:    CString m_strInput;    CStrDirFile();    CStrDirFile(const char szPath[]);    CStrDirFile(CString strPath);public:    bool IsDir(); //    bool IsDir(CString strPath);    bool IsFile();    bool IsFile(CString strPath);    //字符串操作    char* CstringToChar(CString strCstring); //注意防止通过修改char*指向的内容损坏CString结构    CString GetDirOfDir();//获取目录的上一级目录 例如D:\\dir\\ -> D:    CString GetDirOfDir(CString strDirPath);//获取目录的上一级目录 例如D:\\dir\\ -> D:    CString GetDirOfFile(); //获取文件的所在的目录 例如D:\\dir\\a.txt -> D:\\dir\\a    CString GetDirOfFile(CString strFilePath); //获取文件的所在的目录 例如D:\\dir\\a.txt -> D:\\dir\\a    CString GetNameOfDir(CString strDirPath); //获取某个路径的最里层的目录名  例如D:\\dir\\ -> dir    CString GetNameOfFile(CString strFilePath, bool bWithSuffix = true); //获取文件全路径中的文件名 例如D:\\dir\\a.txt -> a.txt    CString FloatToCstring(const float fNum, const int nDigit = 6);    CString IntToCstring(const int nNum);    CString ParseLineInCsv(CString strLine, const int nColumn); //返回csv行的某一列的值    CString ShowTheInput(); //显示当前输入参数    //文件操作    bool IfExistFile();    bool IfExistFile(const char szPath[]);    bool IfExistFile(CString strFilePath);    //后缀相关的字符串注意都使用小写    CString OpenSuffixFile(const char szPath[]); //打开特定类型的文件,返回路径    CString OpenSuffixFile(CString strSuffix = CString("txt")); //打开特定类型的文件,返回路径    CString OpenSuffixFile(const int nSuffix, ...); //打开多种类型的文件,返回路径    CString OpenFile(); //打开任意类型的文件,返回路径    CString OpenTXT(); //打开txt文件,返回路径    int ParseTXTFile(CStringArray* pArrContentInFile);    int ParseTXTFile(const char szPath[], CStringArray* pArrContentInFile);    int ParseTXTFile(CString strFilePath, CStringArray* pArrContentInFile);    int SaveStrToFile(const char szPath[], CString strToSave = CString("hello!"));    int SaveStrToFile(CString strTxtPath, CString strToSave = CString("hello!"));    int SaveTXTFile(const char szPath[], CStringArray& arrContent, bool bAppend = false);    int SaveTXTFile(CString strTxtPath, CStringArray& arrContent, bool bAppend = false);    //文件夹操作    bool IfExistDir();    bool IfExistDir(const char szPath[]);    bool IfExistDir(CString strDirPath);    CString BrowseDir(char szTips[]);    CString BrowseDir(CString strTips = CString("请选择文件夹")); //浏览一个文件夹    CString BrowseDirPlus(CString strTips = CString("请选择文件夹")); //浏览一个文件夹,带新建按钮    int ReadCurrentDirs(CStringArray* pArrDirsInFolder); //读取当前目录下的目录,不包含子目录    int ReadCurrentDirFiles(CStringArray* pArrFilesInFolder, char szSuffix[] = ".txt"); //读取当前目录下的文件,不包含子目录    int ReadDirs(CString strPath, CStringArray* pArrDirsInFolder, bool bIncludeSub = true); //读取当前目录下的目录    int ReadDirFiles(CString strPath, CStringArray* pArrFilesInFolder, char szSuffix[] = ".txt", bool bIncludeSub = true); //读取当前目录下的文件};#endif //_STR_DIR_FILE_

然后是cpp文件:

/* ******* StrFileDir.cpp ******************* 字符串、文件、目录操作函数实现 ********** *//* author: autumoon */#include "StrDirFile.h"/* 构造函数 */CStrDirFile::CStrDirFile():m_strInput("D:\\autumoon"){}CStrDirFile::CStrDirFile(const char szPath[]){    CString strPath(szPath);    m_strInput = strPath;}CStrDirFile::CStrDirFile(CString strPath):m_strInput(strPath){}bool CStrDirFile::IsDir(){    return IfExistDir(m_strInput);}bool CStrDirFile::IsDir(CString strPath){    return IfExistDir(strPath);}bool CStrDirFile::IsFile(){    return IfExistFile(m_strInput);}bool CStrDirFile::IsFile(CString strPath){    return IfExistFile(strPath);}CString CStrDirFile::GetDirOfDir(CString strDirPath){    if (strDirPath.Right(1) == \\)    {        strDirPath = strDirPath.Mid(0, strDirPath.GetLength() - 1);    }    int index = strDirPath.ReverseFind(\\);    if (index != -1)    {        return strDirPath.Mid(0, index);    }    else    {        return strDirPath;    }}CString CStrDirFile::GetDirOfFile(){    return GetDirOfFile(m_strInput);}CString CStrDirFile::GetDirOfFile(CString strFilePath){    if (IsDir(strFilePath))    {        return strFilePath;    }    int index = strFilePath.ReverseFind(\\);    return strFilePath.Mid(0, index);}CString CStrDirFile::OpenFile(){    CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("所有文件(*.*)|*.*||"));    CString szFileName("");    if (IsDir())    {        dlg.m_ofn.lpstrInitialDir = m_strInput;    }    else    {        dlg.m_ofn.lpstrInitialDir = GetDirOfFile();    }    if (dlg.DoModal() == IDOK)    {        szFileName = dlg.GetPathName();    }    return szFileName;}CString CStrDirFile::OpenTXT(){    CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("txt文件(*.txt)|*.txt|所有文件(*.*)|*.*||"));    CString szFileName("");    if (IsDir())    {        dlg.m_ofn.lpstrInitialDir = m_strInput;    }    else    {        dlg.m_ofn.lpstrInitialDir = GetDirOfFile();    }    if (dlg.DoModal() == IDOK)    {        szFileName = dlg.GetFileName();    }    return szFileName;}CString CStrDirFile::OpenSuffixFile(CString strSuffix){    if (strSuffix.Left(1) == .)    {        //delete the ‘.‘ before suffix        strSuffix = strSuffix.Mid(1, strSuffix.GetLength() - 1);    }    CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strSuffix + "文件(*." + strSuffix + ")|*." + strSuffix + "|所有文件(*.*)|*.*||");    CString szFileName("");    if (IsDir())    {        dlg.m_ofn.lpstrInitialDir = m_strInput;    }    else    {        dlg.m_ofn.lpstrInitialDir = GetDirOfFile();    }    if (dlg.DoModal() == IDOK)    {        szFileName = dlg.GetPathName();    }    return szFileName;}CString CStrDirFile::OpenSuffixFile(const int nSuffix, ...){    va_list argp;    va_start(argp, nSuffix);    CStringArray arrSuffixs;    CString strSuffix;    for (int i = 0; i < nSuffix; i++)    {        strSuffix = va_arg(argp, char*);        arrSuffixs.Add(strSuffix);    }    va_end(argp);    //打开多种类型    for (int i = 0; i < nSuffix; i++)    {        if (arrSuffixs[i].Left(1) == .)        {            //delete the ‘.‘ before suffix            arrSuffixs[i] = arrSuffixs[i].Mid(1, arrSuffixs[i].GetLength() - 1);        }    }    CString strTemp("");    for (int i = 0; i < nSuffix; i++)    {        strTemp += arrSuffixs[i] + "文件(*." + arrSuffixs[i] + ")|*." + arrSuffixs[i] + "|";    }    CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strTemp + "所有文件(*.*)|*.*||");    CString szFileName("");    if (IsDir())    {        dlg.m_ofn.lpstrInitialDir = m_strInput;    }    else    {        dlg.m_ofn.lpstrInitialDir = GetDirOfFile();    }    if (dlg.DoModal() == IDOK)    {        szFileName = dlg.GetPathName();    }    return szFileName;}bool CStrDirFile::IfExistFile(){    return IfExistFile(m_strInput);}bool CStrDirFile::IfExistFile(const char szPath[]){    CString strFilePath = CString(szPath);    return IfExistFile(strFilePath);}bool CStrDirFile::IfExistFile(CString strFilePath){    CFile file;    if (file.Open(strFilePath,CFile::modeRead))    {        file.Close();        return true;    }    return false;}CString CStrDirFile::OpenSuffixFile(const char szPath[]){    CString strPath(szPath);    return OpenSuffixFile(strPath);}int CStrDirFile::ParseTXTFile(CStringArray* pArrContentInFile){    return ParseTXTFile(m_strInput, pArrContentInFile);}int CStrDirFile::ParseTXTFile(const char szPath[], CStringArray* pArrContentInFile){    CString strFilePath(szPath);    return ParseTXTFile(strFilePath, pArrContentInFile);}int CStrDirFile::ParseTXTFile(CString strFilePath, CStringArray* pArrContentInFile){    CStdioFile file;    file.Open(strFilePath, CFile::modeRead);    if (!file.m_pStream)    {        return -1;    }    CString szLine;    while(file.ReadString(szLine))    {        pArrContentInFile->Add(szLine);    }    return 0;}int CStrDirFile::SaveStrToFile(const char szPath[], CString strToSave/* = CString("hello!")*/){    CString strPath(szPath);    return SaveStrToFile(strPath, strToSave);}int CStrDirFile::SaveStrToFile(CString strFilePath, CString strToSave/* = CString("hello!")*/){    CStdioFile file;    file.Open(strFilePath, CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate);    file.SeekToEnd();    file.WriteString(strToSave);    file.Close();    return 0;}int CStrDirFile::SaveTXTFile(const char szPath[], CStringArray& arrContent, bool bAppend){    CString strTxtPath(szPath);    SaveTXTFile(strTxtPath, arrContent, bAppend);    return 0;}int CStrDirFile::SaveTXTFile(CString strTxtPath, CStringArray& arrContent, bool bAppend){    CStdioFile file;    if (bAppend)    {        file.Open(strTxtPath, CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate);        file.SeekToEnd();    }    else    {        file.Open(strTxtPath, CFile::modeCreate|CFile::modeReadWrite);    }    for (int i = 0; i < arrContent.GetCount(); i++)    {        file.WriteString(arrContent[i]);    }    file.Close();    return 0;}bool CStrDirFile::IfExistDir(){    return IfExistDir(m_strInput);}bool CStrDirFile::IfExistDir(const char szPath[]){    CString strDirPath(szPath);    return IfExistDir(strDirPath);}bool CStrDirFile::IfExistDir(CString strDirPath){    //本方法不能判断根目录    WIN32_FIND_DATA fd;    bool ret = FALSE;    HANDLE hFind = FindFirstFile(strDirPath, &fd);    if ((hFind != INVALID_HANDLE_VALUE) && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))    {        //目录存在        ret = TRUE;    }    FindClose(hFind);    return ret;}CString CStrDirFile::BrowseDir(char szTips[]/* = "请选择文件夹"*/){    CString strTips = CString(szTips);    return BrowseDir(strTips);}CString CStrDirFile::BrowseDir(CString strTips/* = CString("请选择文件夹")*/){    CString szFileFolderPath;    TCHAR pszPath[MAX_PATH];    BROWSEINFO biFolder;    biFolder.hwndOwner = NULL;    biFolder.pidlRoot = NULL;    biFolder.pszDisplayName = NULL;    biFolder.lpszTitle = strTips;    biFolder.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT;    biFolder.lpfn = NULL;    biFolder.lParam = 0;    LPITEMIDLIST pidl = SHBrowseForFolder(&biFolder);    if (!pidl)    {        return "";    }    else    {        SHGetPathFromIDList(pidl, pszPath);        m_strInput = pszPath;        return pszPath;    }}CString CStrDirFile::BrowseDirPlus(CString strTips/* = CString("请选择文件夹")*/){    CString szFileFolderPath;    TCHAR pszPath[MAX_PATH];    BROWSEINFO biFolder;    biFolder.hwndOwner = NULL;    biFolder.pidlRoot = NULL;    biFolder.pszDisplayName = NULL;    biFolder.lpszTitle = strTips;    biFolder.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;    biFolder.lpfn = NULL;    biFolder.lParam = 0;    LPITEMIDLIST pidl = SHBrowseForFolder(&biFolder);    if (!pidl)    {        return "";    }    else    {        SHGetPathFromIDList(pidl, pszPath);        m_strInput = pszPath;        return pszPath;    }}CString CStrDirFile::GetNameOfDir(CString strDirPath){    if (IsFile(strDirPath))    {        return GetNameOfFile(strDirPath);    }    int index = strDirPath.Trim(\\).ReverseFind(\\);    return strDirPath.Mid(index + 1, strDirPath.GetLength() - index -1);}CString CStrDirFile::GetNameOfFile(CString strFilePath, bool bWithSuffix){    int index = strFilePath.ReverseFind(\\);    CString strFileName = strFilePath.Mid(index + 1, strFilePath.GetLength() - index - 1);    if (bWithSuffix)    {        return strFileName;    }    else    {        int nIndexOfDot = strFileName.ReverseFind(.);        if (nIndexOfDot == -1)        {            return strFileName;        }        else        {            return strFileName.Mid(0, nIndexOfDot);        }    }}CString CStrDirFile::FloatToCstring(const float fNum, const int nDigit){    CString strTemp;    strTemp.Format(_T("%.") + IntToCstring(nDigit) + _T("lf"), fNum);    return strTemp;}CString CStrDirFile::IntToCstring(const int nNum){    CString strTemp;    strTemp.Format(_T("%d"), nNum);    return strTemp;}CString CStrDirFile::ParseLineInCsv(CString strLine, const int nColumn){    CString strContent;    AfxExtractSubString(strContent, strLine, nColumn, ,);    return strContent;}CString CStrDirFile::ShowTheInput(){    return m_strInput;}char* CStrDirFile::CstringToChar(CString strCstring){#ifdef _UNICODE    USES_CONVERSION;    return W2A(strCstring);#else    return (LPSTR)(LPCTSTR)strCstring;#endif}int CStrDirFile::ReadCurrentDirs(CStringArray* pArrDirsInFolder){    if (IsFile())    {        return -1;    }    return ReadDirs(m_strInput, pArrDirsInFolder, false);}int CStrDirFile::ReadCurrentDirFiles(CStringArray* pArrFilesInFolder, char szSuffix[]/* = ".txt"*/){    if (IsFile())    {        return -1;    }    return ReadDirFiles(m_strInput, pArrFilesInFolder, szSuffix, false);}int CStrDirFile::ReadDirs(CString strPath, CStringArray* pArrDirsInFolder, bool bIncludeSub/* = true*/){    CFileFind ff;     DWORD size = 0;     CString szDir = strPath + _T("\\*.*"); //搜索路径,包括所有子目录     BOOL ret = ff.FindFile(szDir);     while (ret)     {         ret = ff.FindNextFile();         if(!ff.IsDots())         {             if(ff.IsDirectory() && !ff.IsHidden())             {                 //子目录结点,递归                pArrDirsInFolder->Add(ff.GetFilePath());                if (bIncludeSub)                {                    ReadDirs(ff.GetFilePath(), pArrDirsInFolder);                }            }         }     }    return 0;}int CStrDirFile::ReadDirFiles(CString strPath, CStringArray* pArrFilesInFolder, char szSuffix[]/* = "txt"*/, bool bIncludeSub/* = true*/){    CFileFind ff;     DWORD size = 0;     CString szDir = strPath + _T("\\*.*"); //搜索路径,包括所有子目录     BOOL ret = ff.FindFile(szDir);     if (IsFile(strPath))    {        return -1;    }    while (ret)     {         ret = ff.FindNextFile();         if(!ff.IsDots())         {             if(ff.IsDirectory() && bIncludeSub)             {                 //子目录结点,递归                ReadDirFiles(ff.GetFilePath(), pArrFilesInFolder, szSuffix, bIncludeSub);            }             else             {                 if (ff.GetFileName().MakeLower().Find(CString(szSuffix)) != -1)                {                    pArrFilesInFolder->Add(ff.GetFilePath());                }            }         }     }    return 0;}

 

MFC常用的字符串、文件、目录操作