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);

}


//mfc 中删除dir目录下的东东
void cmd_rd(CString   dir)
{

   WIN32_FIND_DATA Sr;
   HANDLE Handle;
   int iattr;
   //如果是目录
  iattr=GetFileAttributes(dir);
  if(iattr==FILE_ATTRIBUTE_DIRECTORY)
  {
  try
  {
  Handle=::FindFirstFile(dir+"\\*.*", &Sr);
  }
  catch(...)
  {
  return;
  }
if (Handle)
   {
       do
       {
           if (Sr.cFileName[0]!='.')
{
               if(Sr.dwFileAttributes==FILE_ATTRIBUTE_DIRECTORY)
                   {
                     cmd_rd(dir+" \"+Sr.cFileName);
                   }
               else
               {
::SetFileAttributes(dir+" \"+Sr.cFileName,0);
               ::DeleteFile(dir+" \"+Sr.cFileName);
               }
           }
       } while (::FindNextFile(Handle,&Sr));
       ::FindClose(Handle);
   }
  if(iattr==FILE_ATTRIBUTE_DIRECTORY)
  ::RemoveDirectory(dir);
   }
  else
  {
               ::SetFileAttributes(dir,0);
               ::DeleteFile(dir);
   }
}

//mfc 下的控制台清屏
void cmd_cls(HANDLE hConsole)
{
   COORD coordScreen = { 0, 0 };       // home for the cursor
     DWORD cCharsWritten;
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     DWORD dwConSize;
 
// Get the number of character cells in the current buffer.
 
     if( !GetConsoleScreenBufferIn fo( hConsole, &csbi ))
           return;
     dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
 
     // Fill the entire screen with blanks.
 
     if( !FillConsoleOutputCharact er( hConsole, (TCHAR) ' ',
           dwConSize, coordScreen, &cCharsWritten ))
           return;
 
     // Get the current text attribute.
 
     if( !GetConsoleScreenBufferIn fo( hConsole, &csbi ))
           return;
 
     // Set the buffer's attributes accordingly.
 
     if( !FillConsoleOutputAttribu te( hConsole, csbi.wAttributes,
           dwConSize, coordScreen, &cCharsWritten ))
           return;
 
     // Put the cursor at its home coordinates.
 
     SetConsoleCursorPosition ( hConsole, coordScreen );
}

//MFC中拷贝文件夹
void cmd_xcopy(char* src,char* dst)
{
 
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;
  char tmpsrc[256];
  strcpy(tmpsrc,src);
  strcat(tmpsrc,"\\*.*");
  hFind = FindFirstFile(tmpsrc, &FindFileData);
  if(hFind == INVALID_HANDLE_VALUE)
    return;
  CreateDirectory(dst,0);
  do
  {
  char newdst[256];
  strcpy(newdst,dst);
  if(newdst[strlen(newdst)]!='\\')
    strcat(newdst,"\");
  strcat(newdst,FindFileData.cFileName);

  char newsrc[256];
  strcpy(newsrc,src);
  if(newsrc[strlen(newsrc)]!='\\')
    strcat(newsrc,"\");
  strcat(newsrc,FindFileData.cFileName);
  if(FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
  {
    if(strcmp(FindFileData.cFileName,".")!=0&&strcmp(FindFileData.cFileName,"..")!=0)
    {
      cmd_xcopy(newsrc,newdst);
    }
  }else
  {
    CopyFile(newsrc,newdst,false);
  }
  }while(FindNextFile(hFind,&FindFileData));
       FindClose(hFind);
}
//MFC中创建目录
BOOL   WinCmd::cmd_md(char* lpPath)
{

                 CString pathname = lpPath;
                 if(pathname.Right(1) != "\")
                                   pathname += "\" ;
                 int end = pathname.ReverseFind('\\');
                 int pt = pathname.Find("\");
                 if (pathname[pt-1] == ':')
                                     pt = pathname.Find("\", pt+1);
                 CString path;
    while(pt != -1 && pt<=end)
    {
    path = pathname.Left(pt+1);
    if(_access(path, 0) == -1)
    _mkdir(path);
     pt = pathname.Find("\", pt+1);
    }
  return true;
}



注:转载整理。





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值