C/C++中判断某一文件或目录是否存在

简介:
1.C++很简单的一种办法:
#include  < iostream >
#include 
< fstream >
using   namespace  std;
#define  FILENAME "stat.dat"
int  main()
{
     fstream _file;
     _file.open(FILENAME,ios::
in );
     
if ( ! _file)
     {
         cout
<< FILENAME << " 没有被创建 " ;
      }
      
else
      {
          cout
<< FILENAME << " 已经存在 " ;
      }
      
return   0 ;
}

 

2.利用 c 语言的库的办法:

函数名: access 
功  能: 确定文件的访问权限 
用  法: int access(const char *filename, int amode); 
以前一直没用过这个函数,今天调试程序发现了这个函数,感觉挺好用,尤其是判断一个文件或文件夹是否存在的时候,用不着再find了,文件的话还可以检测读写权限,文件夹的话则只能判断是否存在,下面摘自MSDN:

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

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

Example

/*  ACCESS.C: This example uses _access to check the
 * file named "ACCESS.C" to see if it exists and if
 * writing is allowed.
 
*/

#include  
< io.h >
#include  
< stdio.h >
#include  
< stdlib.h >

void  main(  void  )
{
   
/*  Check for existence  */
   
if ( (_access(  " ACCESS.C " 0  ))  !=   - 1  )
   {
      printf( 
" File ACCESS.C exists  "  );
      
/*  Check for write permission  */
      
if ( (_access(  " ACCESS.C " 2  ))  !=   - 1  )
         printf( 
" File ACCESS.C has write permission  "  );
   }
}
Output
File ACCESS.C existsFile ACCESS.C has write permission

 

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

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

#define  _WIN32_WINNT 0x0400

#include 
" windows.h "

int
main(
int  argc,  char   * argv[])
{
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;

  printf (
" Target file is %s.  " , argv[ 1 ]);

  hFind 
=  FindFirstFile(argv[ 1 ],  & FindFileData);

  
if  (hFind  ==  INVALID_HANDLE_VALUE) {
    printf (
" Invalid File Handle. Get Last Error reports %d  " , GetLastError ());
  } 
else  {
    printf (
" The first file found is %s  " , FindFileData.cFileName);
    FindClose(hFind);
  }

  
return  ( 0 );
}

 

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

 

 

/// 目录是否存在的检查:
bool   CheckFolderExist( const   string   & strPath)
{
    WIN32_FIND_DATA  wfd;
    
bool  rValue  =   false ;
    HANDLE hFind 
=  FindFirstFile(strPath.c_str(),  & wfd);
    
if  ((hFind  !=  INVALID_HANDLE_VALUE)  &&  (wfd.dwFileAttributes  &  FILE_ATTRIBUTE_DIRECTORY))
    {
        rValue 
=   true ;   
    }
    FindClose(hFind);
    
return  rValue;
}

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

#include  < boost / filesystem / operations.hpp >
#include 
< boost / filesystem / path.hpp >
#include 
< boost / filesystem / convenience.hpp >

int  GetFilePath(std:: string   & strFilePath)
{
    
string  strPath;
    
int  nRes  =   0 ;

    
// 指定路径            
    strPath  =   " D:/myTest/Test1/Test2 " ;
    
namespace  fs  =  boost::filesystem;

    
// 路径的可移植
    fs::path full_path( fs::initial_path() );
    full_path 
=  fs::system_complete( fs::path(strPath, fs::native ) );
    
// 判断各级子目录是否存在,不存在则需要创建
     if  (  ! fs::exists( full_path ) )
    {
        
//  创建多层子目录
         bool  bRet  =  fs::create_directories(full_path);
        
if  ( false   ==  bRet)
        {
            
return   - 1 ;
        }

    }
    strFilePath 
=  full_path.native_directory_string();

    
return   0 ;
}
本文转自博客园知识天地的博客,原文链接:C/C++中判断某一文件或目录是否存在,如需转载请自行联系原博主。
相关文章
|
2月前
|
C++
C/C++给文件加crc校验
C/C++给文件加crc校验
47 1
|
2月前
|
存储 C++
基于C++的简易文件压缩与解压缩工具设计与实现
基于C++的简易文件压缩与解压缩工具设计与实现
51 3
|
6天前
|
存储 分布式数据库 API
技术好文:VisualC++查看文件被哪个进程占用
技术好文:VisualC++查看文件被哪个进程占用
|
8天前
|
C++
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
11 0
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
|
10天前
|
C++ iOS开发 开发者
C++一分钟之-文件输入输出(I/O)操作
【6月更文挑战第24天】C++的文件I/O涉及`ifstream`, `ofstream`和`fstream`类,用于读写操作。常见问题包括未检查文件打开状态、忘记关闭文件、写入模式覆盖文件及字符编码不匹配。避免这些问题的方法有:检查`is_open()`、显式关闭文件或使用RAII、选择适当打开模式(如追加`ios::app`)以及处理字符编码。示例代码展示了读文件和追加写入文件的实践。理解这些要点能帮助编写更健壮的代码。
18 2
|
27天前
|
编译器 C语言 C++
C++中.h和.hpp文件有什么区别?
C++中.h和.hpp文件有什么区别?
|
6天前
|
IDE 开发工具 C++
插件:CLion中使用C/C++ Single File Execution插件编译和运行单个文件
插件:CLion中使用C/C++ Single File Execution插件编译和运行单个文件
13 0
|
2月前
|
C++ 数据格式
【C++】C++中的【文件IO流】使用指南 [手把手代码演示] & [小白秒懂]
【C++】C++中的【文件IO流】使用指南 [手把手代码演示] & [小白秒懂]
【C++】C++中的【文件IO流】使用指南 [手把手代码演示] & [小白秒懂]
|
27天前
|
Linux C++
Linux C/C++目录和文件的更多操作
Linux C/C++目录和文件的更多操作
|
27天前
|
Linux C++
Linux C/C++目录操作
Linux C/C++目录操作