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

 更新时间:2013年07月13日 11:04:21   作者:  
以下文章是对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 " );
   }
}

OutputFile 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++类和对象实例解析(二)

    这篇文章主要介绍了C++类和对象,从定义出发再到实例解析,深入的理解C++类和对象,需要的朋友可以参考下
    2015-08-08
  • C++中HTTP 代理服务器的设计与实现详解

    C++中HTTP 代理服务器的设计与实现详解

    代理服务器,即允许一个网络终端(一般为客户端)通过这个服务与另一 个网络终端(一般为服务器)进行非直接的连接,下面我们就来看看如何使用C++设计与实现一个HTTP 代理服务器吧
    2024-01-01
  • VS Code安装及C、C++环境配置详细教程(Windows系统)

    VS Code安装及C、C++环境配置详细教程(Windows系统)

    这篇文章主要介绍了VS Code安装及C、C++环境配置详细教程(Windows系统),本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-02-02
  • C++插件化 NDD源码的插件机制实现解析

    C++插件化 NDD源码的插件机制实现解析

    这篇文章主要介绍了C++插件化 NDD源码的插件机制实现解析,这里再介绍推荐下优秀的国产软件开源项目 NDD(notepad--),一个支持windows/linux/mac的文本编辑器,目标是要国产替换同类软件,需要的朋友可以参考下
    2023-03-03
  • 如何通过指针突破C++类的访问权限

    如何通过指针突破C++类的访问权限

    这篇文章主要介绍了通过指针突破C++类的访问权限,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • C语言代码实现井字棋游戏

    C语言代码实现井字棋游戏

    这篇文章主要为大家详细介绍了C语言代码实现井字棋游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • C++11返回类型后置语法的使用示例

    C++11返回类型后置语法的使用示例

    本篇文章主要介绍了C++11返回类型后置语法的使用示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • Opencv二帧差法检测运动目标与提取轮廓

    Opencv二帧差法检测运动目标与提取轮廓

    这篇文章主要为大家详细介绍了Opencv使用二帧差法检测运动目标与提取轮廓,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-03-03
  • C++实现一行一行读取文本的方法

    C++实现一行一行读取文本的方法

    今天小编就为大家分享一篇C++实现一行一行读取文本的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • 浅谈C++的浅拷贝出现的错误

    浅谈C++的浅拷贝出现的错误

    下面小编就为大家带来一篇浅谈C++的浅拷贝出现的错误。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01

最新评论