首页 > 编程语言 >C++判断文件是否存在的方法汇总

C++判断文件是否存在的方法汇总

时间:2022-10-08 13:46:14浏览次数:43  
标签:文件 return name 汇总 C++ access Test include string

C++判断文件是否存在的方法汇总

1. 使用boost判断文件是否存在

std::string file_path = "file_name";
if (!boost::filesystem::exists(file_path))
  {
    std::cout << "not exist file" << std::endl;
  }

使用boost时需要包含:

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/typeof/typeof.hpp>

 

2. 使用C++标准库判断

  1. #include <fstream> --> 使用ifstream打开文件流,成功则存在,失败则不存在;
  2. #include <stdio.h> --> 以fopen读方式打开文件,成功则存在,否则不存在;
  3. #include <unistd.h> --> 使用access函数获取文件状态,成功则存在,否则不存在
  4. #include <sys/stat.h> --> 使用stat函数获取文件状态,成功则存在,否则不存在
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <string>
#include <iostream>

using namespace std;
bool isFileExists_ifstream(string& name) {
    ifstream f(name.c_str());
    return f.good();
}
bool isFileExists_fopen(string& name) {
    if (FILE *file = fopen(name.c_str(), "r")) {
        fclose(file);
        return true;
    } else {
        return false;
    }   
}
bool isFileExists_access(string& name) {
    return (access(name.c_str(), F_OK ) != -1 );
}
bool isFileExists_stat(string& name) {
  struct stat buffer;   
  return (stat(name.c_str(), &buffer) == 0); 
}

 其中acces函数参数意义如下:

/* Values for the second argument to access.
   These may be OR'd together.  */
#define	R_OK	4		/* Test for read permission.  */
#define	W_OK	2		/* Test for write permission.  */
#define	X_OK	1		/* Test for execute permission.  */
#define	F_OK	0		/* Test for existence.  */

/* Test for access to NAME using the real UID and real GID.  */
extern int access (const char *__name, int __type) __THROW __nonnull ((1));

传入的两个变量分别是文件夹的路径,以及需要查询的权限,6代表读写权限,0代表存在与否。

std::string folderpath = "/<the_folder_path>";
if(access(folderpath.c_str(), 0)){
 	std::cout<<"folder does not exist! Will create a new one!" <<std::endl;
        }

 

标签:文件,return,name,汇总,C++,access,Test,include,string
From: https://www.cnblogs.com/RobustFresher/p/16768655.html

相关文章