C++文件目录检测及新建
在Windows 及 Linux 平台下code如下:
#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 = "/home/XXX"; //文件夹路径
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;
}
文件夹删除代码如下:
#ifdef WIN32 int flag = mkdir(dir.c_str()); //Windows创建文件夹 #else int flag = mkdir(dir.c_str(), S_IRWXU); //Linux创建文件夹 #endif //将上面代码改为如下即可: int flag = rmdir(dir.c_str());
记录每天生活的点点滴滴,呵呵呵呵呵呵

浙公网安备 33010602011771号