Windows需要如下头文件:
#include <direct.h>
#include <io.h>
Linux需要如下头文件:
#include <sys/io.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
具体实现过程如下:文章来源:https://www.toymoban.com/news/detail-523582.html
#ifdef WIN32 //Windows
#include <direct.h>
#include <io.h>
#else // Linux
#include <sys/io.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#endif
#include <string>
#include <iostream>
int main()
{
std::string dir = PATH; //PAHT为文件夹路径
if (access(dir.c_str(), 0) == -1)
{ //判断该文件夹是否存在
#ifdef WIN32
int flag = mkdir(dir.c_str()); //Windows创建文件夹
#else
int flag = mkdir(dir.c_str(), S_IRWXU); //Linux创建文件夹
#endif
if (flag == 0)
{ //创建成功
std::cout << "Create directory successfully." << std::endl;
}
else
{ //创建失败
std::cout << "Fail to create directory." << std::endl;
throw std::exception();
}
}
else
{
std::cout << "This directory already exists." << std::endl;
}
return 0;
}
如果需要删除则将mkdir替换为rkdir即可文章来源地址https://www.toymoban.com/news/detail-523582.html
到了这里,关于C++判断文件夹是否存在,不存在则创建(linux和windows)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!