VC中判断目录,文件是否存在,创建目录,求目录或文件大小的方法

本文介绍如何在C++中进行目录、文件的存在性检查、创建目录、获取文件大小和目录大小的操作,并提供了相关代码示例。

目录是否存在检查:

 

  1. BOOL FolderExist(CString strPath)  
  2. {  
  3.    WIN32_FIND_DATA wfd;  
  4.     BOOL rValue= FALSE;  
  5.     HANDLE hFind= FindFirstFile(strPath, &wfd);  
  6.     if((hFind!=INVALID_HANDLE_VALUE)&&  
  7.         (wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY))  
  8.     {  
  9.        rValue = TRUE;  
  10.     }  
  11.    FindClose(hFind);  
  12.     returnrValue;  
  13. }  

 

文件存在性检查:
注意,该函数是检查当前目录下是否有该文件
如果想检查其他目录下是否有该文件,则在参数中输入该文件的完整路径即可

 

  1. BOOL FileExist(CString strFileName)  
  2. {  
  3.     CFileFindfFind;  
  4.     returnfFind.FindFile(strFileName);  
  5. }  

 

创建目录:

  1. BOOL CreateFolder(CString strPath)  
  2. {  
  3.    SECURITY_ATTRIBUTES attrib;  
  4.    attrib.bInheritHandle = FALSE;  
  5.    attrib.lpSecurityDescriptor = NULL;  
  6.    attrib.nLength = sizeof(SECURITY_ATTRIBUTES);  
  7.    //上面定义的属性可以省略  
  8.     //直接使用return::CreateDirectory(path, NULL);即可  
  9.     return::CreateDirectory(strPath, &attrib);  
  10. }  

 

 



文件大小:

  1. DWORDGetFileSize(CString filepath)  
  2. {  
  3.    WIN32_FIND_DATA fileInfo;  
  4.     HANDLEhFind;  
  5.     DWORDfileSize;  
  6.     CStringfilename;  
  7.     filename =filepath;  
  8.     hFind =FindFirstFile(filename,&fileInfo);  
  9.     if(hFind !=INVALID_HANDLE_VALUE)  
  10.        fileSize =fileInfo.nFileSizeLow;  
  11.      
  12.    FindClose(hFind);  
  13.     returnfilesize;  
  14. }  

当然在CFileFind里面有GetLength()函数,也可以求得。


文件夹大小
  1. DWORDCVCTestDlg::GetDirSize(CString strDirPath)  
  2. {  
  3.     CStringstrFilePath;  
  4.    DWORD   dwDirSize = 0;  
  5.      
  6.     strFilePath+= strDirPath;  
  7.     strFilePath+= "\\*.*";  
  8.      
  9.     CFileFindfinder;  
  10.     BOOL bFind =finder.FindFile(strFilePath);  
  11.     while(bFind)  
  12.     {  
  13.        bFind =finder.FindNextFile();  
  14.        if(!finder.IsDots())  
  15.        {  
  16.           CStringstrTempPath = finder.GetFilePath();  
  17.           if(!finder.IsDirectory())  
  18.           {  
  19.              dwDirSize +=finder.GetLength();  
  20.           }  
  21.           else  
  22.           {  
  23.              dwDirSize +=GetDirSize(strTempPath);  
  24.           }  
  25.        }  
  26.     }  
  27.    finder.Close();  
  28.     returndwDirSize;  



转自:http://blog.youkuaiyun.com/wangjieest/article/details/7000640
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值