C++检测文件或者目录是否存在

本文介绍了几种检查文件或目录是否存在的方法,包括使用C++标准库、C语言库函数access、Windows API函数FindFirstFile及Boost库的filesystem类库。

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(...):

#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++ 中,判断目录是否存在的实现通常依赖于标准库 `<filesystem>` 或者 POSIX 提供的相关 API。以下是两种常见的实现方式及其代码示例。 --- #### 1. 使用 `<filesystem>`(C++17 及以上) 自 C++17 引入 `<filesystem>` 标准库以来,判断目录是否存在变得非常简单直观。该方法跨平台支持良好,推荐优先使用。 ```cpp #include <iostream> #include <filesystem> bool is_directory_exists(const std::string& path) { return std::filesystem::exists(path) && std::filesystem::is_directory(path); } int main() { std::string dir_path = "/path/to/directory"; // 替换为目标路径 if (is_directory_exists(dir_path)) { std::cout << "Directory exists." << std::endl; } else { std::cout << "Directory does not exist." << std::endl; } return 0; } ``` 此代码中: - `std::filesystem::exists` 检查路径是否存在。 - `std::filesystem::is_directory` 进一步确认路径是否目录[^3]。 --- #### 2. 使用 POSIX 函数 (`stat`) 对于不支持 C++17 的编译器环境,或者需要更底层控制的情况下,可以采用 POSIX 提供的 `stat` 函数来检测目录存在状态。 ```cpp #include <iostream> #include <sys/stat.h> #include <unistd.h> bool is_directory_exists(const char* path) { struct stat info; if (stat(path, &info) != 0) { return false; // 路径不存在或无法访问 } return (info.st_mode & S_IFDIR) != 0; // 检查是否目录 } int main() { const char* dir_path = "/path/to/directory"; // 替换为目标路径 if (is_directory_exists(dir_path)) { std::cout << "Directory exists." << std::endl; } else { std::cout << "Directory does not exist." << std::endl; } return 0; } ``` 此代码中: - `stat` 函数获取路径的状态信息并存储到结构体 `struct stat` 中。 - `(info.st_mode & S_IFDIR)` 用于验证路径是否具有目录属性[^4]。 --- #### 3. Windows 平台下的实现 如果目标平台是 Windows,还可以使用 `_access_s` 函数配合标志位检查路径性质。 ```cpp #include <iostream> #include <io.h> // _access_s 定义于此头文件 bool is_directory_exists(const char* path) { DWORD attributes = GetFileAttributesA(path); if (attributes == INVALID_FILE_ATTRIBUTES) { return false; // 路径无效或不可访问 } return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; // 检查是否目录 } int main() { const char* dir_path = "C:\\path\\to\\directory"; // 替换为目标路径 if (is_directory_exists(dir_path)) { std::cout << "Directory exists." << std::endl; } else { std::cout << "Directory does not exist." << std::endl; } return 0; } ``` 此代码中: - `GetFileAttributesA` 返回文件目录的属性值。 - `FILE_ATTRIBUTE_DIRECTORY` 是一个特定标志,表示路径指向的是目录[^5]。 --- ### 总结 三种方法各有适用场景: - 如果项目能够使用 C++17 或更高版本的标准库,则建议首选 `<filesystem>` 方案,因其简洁易懂且具备良好的可移植性。 - 对于低级操作系统交互需求较高的场合,POSIX 的 `stat` 和 Windows 的 `GetFileAttributesA` 更加适合,但需要注意平台差异带来的额外复杂度。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值