---
title: "VC++文件操作"
author: "feihen"
date: "2010-12-30T17:40:35Z"
tags: ["MFC", "Pascal", "VC++"]
categories: ["编程语言"]
slug: "vc"
draft: false
lastmod: "2010-12-30T17:40:35Z"
id: 856147
url: "https://feihen.iteye.com/blog/856147"
---

**文件属性相关**

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

 

 

 

 

 

２．文件的移动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 文件移动准备，下次启动系统时执行移动作业。

３．删除文件

API：

BOOL DeleteFile( LPCTSTR lpFileName );

MFC：

static void PASCAL CFile::Remove(LPCTSTR lpszFileName);

４．文件更名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-&gt;m\_cause);**

    **pEx-&gt;Delete();**

**}**

**遍历文件目录**

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

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

}

**文件目录操作**

１．创建目录（ＡＰＩ）

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

２．删除目录（ＡＰＩ）

BOOL RemoveDirectory( LPCTSTR lpPathName );

３．判断目录是否存在（Shell Function）

#include &lt;shlwapi.h&gt;#pragma comment(lib, "shlwapi.lib") if (PathIsDirectory(\_T("d:\\\\temp"))) AfxMessageBox(\_T("存在"));else AfxMessageBox(\_T("不存在"));

 

 

 

 

 

４．取得当前目录（ＡＰＩ）

DWORD GetCurrentDirectory( DWORD nBufferLength, LPTSTR lpBuffer );

５．取得执行文件所在目录（ＡＰＩ）

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

６．取得功能目录（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);  
    }

７．选择目录用的对话框界面

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

 

#include&lt;shlobj.h&gt;

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