MFC 文件,文件夹操作

VC++ MFC文件,文件夹操作整理

文件属性相关

1.判断文件是否存在

利用CFile类和CFileStatus类判断

CFileStatus filestatus;
if (CFile::GetStatus(_T("d://softist.txt"), filestatus))
    AfxMessageBox(_T("文件存在"));
else
    AfxMessageBox(_T("文件不存在"));

利用 CFileFind 类判断

CFileFind filefind;
CString strPathname = _T("d://softist.txt");
if(filefind.FindFile(strPathname))
    AfxMessageBox(_T("文件存在"));
else
    AfxMessageBox(_T("文件不存在"));

利用 API 函数 FindFirstFile 判断,这个函数还可以判断文件属性,日期,大小等属性。例:

WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(_T("d://softist.txt"), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) 
{
    AfxMessageBox(_T("文件不存在"));
} 
else 
{
    AfxMessageBox(_T("文件存在"));
    FindClose(hFind);
}

2 .文件日期操作。下面是取得 "d://softist.txt" 的文件修改时间, TRACE 以后,再把文件修改时间改成  2000-12-03 12:34:56

HANDLE     hFile;
FILETIME   filetime;
FILETIME   localtime;
SYSTEMTIME systemtime;
 
hFile = CreateFile(_T("d://softist.txt"), GENERIC_READ | GENERIC_WRITE,
     0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
 
if (hFile != INVALID_HANDLE_VALUE)
{
    GetFileTime(hFile, NULL, NULL, &filetime);      //取得UTC文件时间
    FileTimeToLocalFileTime(&filetime, &localtime); //换成本地时间
    FileTimeToSystemTime(&localtime, &systemtime);  //换成系统时间格式
 
    TRACE("%04d-%02d-%02d %02d:%02d:%02d/r/n",
          systemtime.wYear, systemtime.wMonth, systemtime.wDay,
          systemtime.wHour, systemtime.wMinute, systemtime.wSecond);
 
    //把文件时间修改成 2000-12-03 12:34:56
    systemtime.wYear = 2000; systemtime.wMonth = 12; systemtime.wDay = 3;
    systemtime.wHour = 12; systemtime.wMinute = 34; systemtime.wSecond = 56;
    SystemTimeToFileTime(&systemtime, &localtime); //换成文件时间格式
    LocalFileTimeToFileTime(&localtime, &filetime); //换成UTC时间
    SetFileTime(hFile, NULL, NULL, &filetime);  //设定UTC文件时间
    CloseHandle(hFile);
}

3 .设置文件属性

BOOL SetFileAttributes( LPCTSTR lpFileName, DWORD dwFileAttributes );

dwFileAttributes 的意义

FILE_ATTRIBUTE_ARCHIVE   保存文件

FILE_ATTRIBUTE_HIDDEN    隐藏文件

FILE_ATTRIBUTE_NORMAL   通常文件

FILE_ATTRIBUTE_READONLY 只读文件

FILE_ATTRIBUTE_SYSTEM   系统文件

例:

SetFileAttributes(_T("d://softist.txt", FILE_ATTRIBUTE_READONLY);

文件的复制,移动,删除,更名

1.文件的复制API

BOOL CopyFile(LPCTSTR lpExistingFileName, LPCTSTR lpNewFileName, BOOL bFailIfExists);

bFailIfExists 用来制定如果目标文件已经存在时,是否中止复制操作,返回 FALSE 。例,把 "d://softist1.txt" 复制到 "d://softist2.txt" ,即使 "d://softist2.txt" 已经存在。

BOOL bRet = CopyFile(_T("d://softist1.txt"), _T("d://softist2.txt"), FALSE);

2.文件的移动 API

BOOL MoveFile( LPCTSTR lpExistingFileName, LPCTSTR lpNewFileName );

这个函数可以移一个文件,或目录(包括子目录),例

MoveFile(_T("d://softist.txt"), _T("d://softist2.txt"));

下面的 API 带着选项 dwFlags  ,移动文件,或目录(包括子目录)。

BOOL MoveFileEx( LPCTSTR lpExistingFileName, LPCTSTR lpNewFileName, DWORD dwFlags );

dwFlags的意义: 

MOVEFILE_REPLACE_EXISTING 如果目标文件存在是否替代它 

MOVEFILE_DELAY_UNTIL_REBOOT 文件移动准备,下次启动系统时执行移动作业。

3.删除文件

API

BOOL DeleteFile( LPCTSTR lpFileName );
MFC
static void PASCAL CFile::Remove(LPCTSTR lpszFileName);
4.文件更名 MFC

TCHAR* pOldName = _T("Oldname_File.dat");
TCHAR* pNewName = _T("Renamed_File.dat");
try
{
    CFile::Rename(pOldName, pNewName);
}
catch(CFileException* pEx )
{
    TRACE(_T("File %20s not found, cause = %d/n"), pOldName,
    pEx->m_cause);
    pEx->Delete();
}

遍历文件目录

遍历文件目录,即把一个目录里的文件以及子目录里的文件名都取出来。本文是CFileFind类的使用例的笔记。下面的程序是从一个目录出发,把这个目录里的所有成员按着层次TRACEDEBUG输出画面。

void TravelFolder(CString strDir, int nDepth)
{
    CFileFind filefind;                                         //声明CFileFind类型变量
    CString strWildpath = strDir + _T("//*.*");     //所有文件都列出。
    if(filefind.FindFile(strWildpath, 0))                    //开始检索文件
    {
        BOOL bRet = TRUE;
        while(bRet)
        {
            bRet = filefind.FindNextFile();                 //枚举一个文件
            if(filefind.IsDots())                                 //如果是. 或 .. 做下一个
                continue;
            for (int i = 0; i < nDepth; i ++)                 //层次空格打印
            {
                TRACE(_T("    "));
            }
            if(!filefind.IsDirectory())                          //不是子目录,把文件名打印出来
            {
                CString strTextOut = strDir + CString(_T("//")) + filefind.GetFileName();
                TRACE(_T("file = %s/r/n"), strTextOut);
            }
            else                                                    //如果是子目录,递归调用该函数
            {
                CString strTextOut = strDir + CString(_T("//")) + filefind.GetFileName();
                TRACE(_T("dir = %s/r/n"), strTextOut);
                TravelFolder(strTextOut, nDepth + 1);//递归调用该函数打印子目录里的文件
            }
        }
        filefind.Close();
    }
}
//测试,把d盘的/temp里的所有文件和子目录打印到DEBUG输出画面。
void Test()
{
    TravelFolder(CString(_T("d://temp")), 0);
}

文件目录操作

1.创建目录(API)

BOOL CreateDirectory(LPCTSTR pstrDirName);//pstrDirName是全路径

2.删除目录(API)

BOOL RemoveDirectory( LPCTSTR lpPathName );

3.判断目录是否存在( Shell Function
#include <shlwapi.h>#pragma comment(lib, "shlwapi.lib") if (PathIsDirectory(_T("d://temp"))) AfxMessageBox(_T("存在"));else AfxMessageBox(_T("不存在"));

4.取得当前目录(API)
DWORD GetCurrentDirectory( DWORD nBufferLength, LPTSTR lpBuffer );

5.取得执行文件所在目录(API)

DWORD GetModuleFileName( HMODULE hModule, LPTSTR lpFilename, DWORD nSize );

6.取得功能目录( Shell Function

BOOL SHGetSpecialFolderPath( HWND hwndOwner,  LPTSTR lpszPath, int nFolder, BOOL fCreate);

例:读取我的档案目录

 TCHAR szDirFile[1024];
    memset(szDirFile, 0, sizeof(szDirFile));
    BOOL bRet = SHGetSpecialFolderPath(NULL,szDirFile,CSIDL_PERSONAL,true);
    if (bRet)
    {
        AfxMessageBox(szDirFile);
    }

7.选择目录用的对话框界面

利用Shell Function可以打出选择目录用的对话框界面

#include<shlobj.h>
INT CALLBACK _BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM pData)
{
    TCHAR szDir[MAX_PATH];
    switch(uMsg)
    {
    case BFFM_INITIALIZED:
        // WParam is TRUE since you are passing a path.
        // It would be FALSE if you were passing a pidl.
        SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)pData);
        break;
    case BFFM_SELCHANGED:
        // Set the status window to the currently selected path.
        if (SHGetPathFromIDList((LPITEMIDLIST)lParam ,szDir))
        {
            SendMessage(hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)szDir);
        }
        break;
    }
    return 0;
}
 
CString GetFolderFullpath(LPCTSTR lpszDefault)
{
    TCHAR buffDisplayName[MAX_PATH];
    TCHAR fullpath[MAX_PATH];
    BROWSEINFO  browseinfo;
    LPITEMIDLIST lpitemidlist;
 
    ZeroMemory(&browseinfo, sizeof( BROWSEINFO ));
    browseinfo.pszDisplayName = buffDisplayName ;
    browseinfo.lpszTitle = _T("请选择目录");
    browseinfo.ulFlags = BIF_RETURNONLYFSDIRS;
    browseinfo.lParam = (LPARAM)lpszDefault;
    browseinfo.lpfn = _BrowseCallbackProc;
 
    if(!(lpitemidlist = SHBrowseForFolder(&browseinfo)))
    {
        AfxMessageBox(_T("没有选择目录"));
        return CString(_T(""));
    }
    else
    {
        SHGetPathFromIDList(lpitemidlist, fullpath);      
        CoTaskMemFree(lpitemidlist);
        return CString(fullpath);
    }
}
 
void CTest77Dlg::OnBnClickedButton1()
{
    CString strFolderFullpath = GetFolderFullpath(_T("d://Temp"));
    if (strFolderFullpath != _T(""))
        AfxMessageBox(strFolderFullpath);
}




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值