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++基于prim实现迷宫生成

    C++基于prim实现迷宫生成

    这篇文章主要为大家详细介绍了C++基于prim实现迷宫生成,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-05-05
  • C++ Log日志类轻量级支持格式化输出变量实现代码

    C++ Log日志类轻量级支持格式化输出变量实现代码

    这篇文章主要介绍了C++ Log日志类轻量级支持格式化输出变量实现代码,需要的朋友可以参考下
    2019-04-04
  • C++版图书管理系统

    C++版图书管理系统

    这篇文章主要为大家详细介绍了C++版图书管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • vs2019 MFC实现office界面的画图小项目

    vs2019 MFC实现office界面的画图小项目

    本文主要介绍了vs2019 MFC实现office界面的画图小项目,对大家入门有一定的帮助,需要的朋友们下面随着小编来一起学习学习吧
    2021-06-06
  • C++实现并优化异常系统

    C++实现并优化异常系统

    异常处理是C++的一项语言机制,用于在程序中处理异常事件,下面这篇文章主要给大家介绍了关于C++中异常的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • OpenCV使用GrabCut实现抠图功能

    OpenCV使用GrabCut实现抠图功能

    Grabcut是基于图割(graph cut)实现的图像分割算法,它需要用户输入一个bounding box作为分割目标位置,实现对目标与背景的分离/分割。本文将使用GrabCut实现抠图功能,需要的可以参考一下
    2023-02-02
  • 详解C++编程中对二进制文件的读写操作

    详解C++编程中对二进制文件的读写操作

    这篇文章主要介绍了C++编程中对二进制文件的读写操作,是C++入门学习中的基础知识,需要的朋友可以参考下
    2015-09-09
  • 详细讲解C语言中的数据以及位运算

    详细讲解C语言中的数据以及位运算

    这篇文章主要为大家详细介绍了C语言中数据表示方法以及位运算的相关知识点,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-06-06
  • 解决Devc++运行窗口中文乱码的实现步骤

    解决Devc++运行窗口中文乱码的实现步骤

    本文主要介绍了如何解决Devc++运行窗口中文乱码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • C语言贪吃蛇经典小游戏

    C语言贪吃蛇经典小游戏

    这篇文章主要为大家详细介绍了C语言贪吃蛇经典小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01

最新评论