C/C++判断文件/文件夹是否存在

本文详细介绍了在C++和C语言中通过多种方法判断文件和文件夹的存在性及访问权限,包括使用`CreateDirectory`、`_access`函数、`FindFirstFile`API以及Boost库的`exists`函数等,提供了丰富的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接,感谢原作者

在使用PathFileExists输入参数LPCTSTR出错!!!下面是转来的方法,还没有验证!


判断文件夹是否存在:

     1.用CreateDirectory(".\\FileManege",NULL);如果文件夹FileManege不存在,则创建。
     2.或者if(_access(".\\FileManege",0)==-1),表示FileManege不存在。
     3.或者BOOL PathIsDirectory(LPCTSTR pszPath);

二、判断文件是否存在:
     1.用if((file=fopen(".\\FileManege\\F\\F.dat","rb"))==NULL)
         file=fopen(".\\FileManege\\F\\F.dat","ab+"); // 先判断有无文件,没的话新建一个
     2.用if(_access(".\\FileManege\\F\\F.dat",0)==-1),表示文件不存在。


       函数int _access( const char *path, int mode );可以判断文件或者文件夹的mode属性
       mode=00;//Existence only
       mode=02;//Write permission
       mode=04;//Read permission
       mode=06;//Read and write permission
       需要包含头文件<io.h>。


下面是从优快云论坛转来的


1.C++很简单的一种办法:
[cpp]  view plain copy
  1. #include  < iostream >   
  2. #include  < fstream >   
  3. using   namespace  std;  
  4. #define  FILENAME "stat.dat"   
  5. int  main()  
  6. {  
  7.      fstream _file;  
  8.      _file.open(FILENAME,ios:: in );  
  9.       if ( ! _file)  
  10.      {  
  11.          cout << FILENAME << " 没有被创建 " ;  
  12.       }  
  13.        else   
  14.       {  
  15.           cout << FILENAME << " 已经存在 " ;  
  16.       }  
  17.        return   0 ;  
  18. }  
2.利用 c 语言的库的办法:

函数名: _access 
功  能: 确定文件的访问权限 
用  法: int access(const char *filename, int amode);

Determine file-access permission.

int _access( const char *path, int mode );

int _waccess( const wchar_t *path, int mode );

参考MSDN

Return Value

Each of these functions returns 0 if the file has the given mode. The function returns –1 if the named file does not exist or is not accessible in the given mode; in this case, errno is set as follows:

EACCES

Access denied: file’s permission setting does not allow specified access.

ENOENT

Filename or path not found.

Parameters

path

File or directory path

mode

Permission setting

Remarks

When used with files, the _access function determines whether the specified file exists and can be accessed as specified by the value of mode . When used with directories, _access determines only whether the specified directory exists; in Windows NT, all directories have read and write access.

mode Value            Checks File For 
00                              Existence only 
02                              Write permission 
04                              Read permission 
06                              Read and write permission

 

Generic-Text Routine Mappings

TCHAR.H Routine_UNICODE & _MBCS Not Defined_MBCS Defined_UNICODE Defined
_taccess_access_access_waccess

Example

 

[cpp]  view plain copy
  1. /* ACCESS.C: This example uses _access to check the 
  2.  * file named "ACCESS.C" to see if it exists and if 
  3.  * writing is allowed. 
  4.  */  
  5.   
  6. #include  <io.h>  
  7. #include  <stdio.h>  
  8. #include  <stdlib.h>  
  9.   
  10. void main( void )  
  11. {  
  12.    /* Check for existence */  
  13.    if( (_access( "ACCESS.C", 0 )) != -1 )  
  14.    {  
  15.       printf( "File ACCESS.C exists/n" );  
  16.       /* Check for write permission */  
  17.       if( (_access( "ACCESS.C", 2 )) != -1 )  
  18.          printf( "File ACCESS.C has write permission/n" );  
  19.    }  
  20. }  

Output

File ACCESS.C exists File ACCESS.C has write permission  

 

 

3.在windows平台下用API函数FindFirstFile(...):

(1)检查文件是否存在:

[cpp]  view plain copy
  1. #define  _WIN32_WINNT 0x0400   
  2.   
  3. #include  <windows.h>   
  4.   
  5. int main( int  argc,  char   * argv[])  
  6. {  
  7.   WIN32_FIND_DATA FindFileData;  
  8.   HANDLE hFind;  
  9.   
  10.   printf ( " Target file is %s. " , argv[ 1 ]);  
  11.   
  12.   hFind  =  FindFirstFile(argv[ 1 ],  & FindFileData);  
  13.   
  14.    if  (hFind  ==  INVALID_HANDLE_VALUE) {  
  15.     printf ( " Invalid File Handle. Get Last Error reports %d " , GetLastError ());  
  16.   }  else  {  
  17.     printf ( " The first file found is %s " , FindFileData.cFileName);  
  18.     FindClose(hFind);  
  19.   }  
  20.   
  21.    return  ( 0 );  
  22. }  

 

(2)检查某一目录是否存在:

[cpp]  view plain copy
  1. /// 目录是否存在的检查:   
  2. bool   CheckFolderExist( const   string   & strPath)  
  3. {  
  4.     WIN32_FIND_DATA  wfd;  
  5.      bool  rValue  =   false ;  
  6.     HANDLE hFind  =  FindFirstFile(strPath.c_str(),  & wfd);  
  7.      if  ((hFind  !=  INVALID_HANDLE_VALUE)  &&  (wfd.dwFileAttributes  &  FILE_ATTRIBUTE_DIRECTORY))  
  8.     {  
  9.         rValue  =   true ;     
  10.     }  
  11.     FindClose(hFind);  
  12.      return  rValue;  
  13. }  

 

4.使用boost的filesystem类库的exists函数

[cpp]  view plain copy
  1. #include  < boost / filesystem / operations.hpp >   
  2. #include  < boost / filesystem / path.hpp >   
  3. #include  < boost / filesystem / convenience.hpp >   
  4.   
  5. int  GetFilePath(std:: string   & strFilePath)  
  6. {  
  7.      string  strPath;  
  8.      int  nRes  =   0 ;  
  9.   
  10.      // 指定路径               
  11.     strPath  =   " D:/myTest/Test1/Test2 " ;  
  12.      namespace  fs  =  boost::filesystem;  
  13.   
  14.      // 路径的可移植   
  15.     fs::path full_path( fs::initial_path() );  
  16.     full_path  =  fs::system_complete( fs::path(strPath, fs::native ) );  
  17.      // 判断各级子目录是否存在,不存在则需要创建   
  18.      if  (  ! fs::exists( full_path ) )  
  19.     {  
  20.          //  创建多层子目录   
  21.          bool  bRet  =  fs::create_directories(full_path);  
  22.          if  ( false   ==  bRet)  
  23.         {  
  24.              return   - 1 ;  
  25.         }  
  26.   
  27.     }  
  28.     strFilePath  =  full_path.native_directory_string();  
  29.   
  30.      return   0 ;  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值