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>
具体实现过程如下:
#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即可