1. Linux系统,c语言环境
#include <unistd.h>
int access(const char *pathname, int mode);
参数说明:
pathname --文件或文件夹的路径
mode --模式
R_OK 只判断是否有读权限
W_OK 只判断是否有写权限
X_OK 判断是否有执行权限
F_OK 只判断是否存在
返回值--如果指定的存取方式有效,则函数返回0,否则函数返回-1
上代码:
#include <iostream>
#include <string>
#include <unistd.h>
int main()
{
std::string path("/root/user/work/test.cpp");
int ret = access(path.c_str(), F_OK);
if(ret != 0)
{
std::cout << "文件不存在" << std::endl;
}
return 0;
}
2.Linux系统,c++语言环境,需要c++17
头文件#include <experimental/filesystem>
exists函数源码
inline bool
exists(file_status __s) noexcept
{ return status_known(__s) && __s.type() != file_type::not_found; }
inline bool
exists(const path& __p)
{ return exists(status(__p)); }
inline bool
exists(const path& __p, error_code& __ec) noexcept
{
auto __s = status(__p, __ec);
if (status_known(__s))
{
__ec.clear();
return __s.type() != file_type::not_found;
}
return false;
}
参数:
| _s | - | file status to check |
| _p | - | path to examine |
| _ec | - | out-parameter for error reporting in the non-throwing overload |
返回值:
true -- if the given path or file status corresponds to an existing file or directory
false -- otherwise.
代码:
#include <iostream>
#include <string>
#include <experimental/filesystem>
int main()
{
std::string path("/root/user/work/test.cpp");
int ret = std::experimental::filesystem::exists(path);
if(ret != true)
{
std::cout << "文件不存在" << std::endl;
}
return 0;
}
3.boost,C++
boost::filesystem::exists(file_path)
代码
#include<boost/filesystem.hpp>
{
boost::filesystem::path file_path = "file";
if(boost::filesystem::exists(file_path)) { //判断路径是否存在
std::cout << "文件存在" << std::endl;
}
else {
boost::filesystem::create_directory(file_path); //文件夹不存在则创建一个
boost::filesystem::create_directories(file_path);
}
}

本文介绍了三种在Linux环境下检查文件是否存在的方法:使用C语言的access函数、C++17的experimental/filesystem库中的exists函数及Boost库的boost::filesystem::exists函数。

1万+

被折叠的 条评论
为什么被折叠?



