本文共 1236 字,大约阅读时间需要 4 分钟。
函数access可以判断文件或文件夹是否存在。mkdir可以创建文件夹,但不能递归创建。这里写了一个函数mkdirp用于递归创建文件夹。
#include#include #include #include using namespace std;int mkdirp(const string path) { string temp_path = path; if(temp_path[0] == '/') if(temp_path.substr(0, 5).compare("/home") != 0) return -1; for(size_t i=1; i > temp_path) { prefix += temp_path; //cout << prefix << endl; if(access(prefix.c_str(), F_OK) != 0) if(mkdir(prefix.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRWXG | S_IRWXO) !=0) return -1; prefix += '/'; } return 0;}int main() { const string output_dir = "/home/ /video/1/2/asd"; cout << mkdirp(output_dir) << endl;}
还可以使用system函数执行系统命令递归地创建文件夹:
#include#include #include using namespace std;void mkdirp(const string Path) { if(access(Path.c_str(), F_OK) == -1) { string dir = "mkdir -p " + Path; system(dir.c_str()); }}int main() { const string output_dir = "/home/omen/video/1/2/asd"; mkdirp(output_dir);}
转载地址:http://dcdnn.baihongyu.com/