如何以更有效的方式在 c++ 中创建文件夹
How to create a folder in c++ in a more efficient way?
在我的C++项目中,我提供了一个选项来备份为存储记录而创建的文件,该选项通过在用户给定的路径中创建一个文件夹来备份该文件在该目录中。相同的代码如下:
void backup()
{
char a[40],c[40],b[40];
product p1;
clrscr();
ifstream fp1("products.dat", ios::binary);
ifstream fp2("purchase.dat",ios::binary);
ifstream fp3("sales.dat",ios::binary);
if(fp1==NULL || fp2==NULL || fp3==NULL)
{
cout<<"ntError-No or Incomplete Database...";
}
else
{
cout<<d_line;
cout<<"ttt Database backup";
cout<<"nttt -------- ------";
cout<<line;
cout<<"ntEnter the Directory in which you want to create backup:";
gets(a);
strcpy(b,a);
strcpy(c,a);
strcat(a,"/backup_b");
strcat(b,"/backup_b");
strcat(c,"/backup_b");
mkdir(a);
strcat(a,"/products.dat");
strcat(b,"/purchase.dat");
strcat(c,"/sales.dat");
ofstream fp1_t(a, ios::binary | ios::trunc);
ofstream fp2_t(b, ios::binary | ios::trunc);
ofstream fp3_t(c, ios::binary | ios::trunc);
if(fp1_t==NULL || fp2_t==NULL ||fp3_t==NULL)
{
cout<<"nntError During creating backup...n";
}
else
{
while(!fp1.eof())
{
fp1.read((char *) &p1,sizeof(struct product));
if(fp1.fail())
{
break;
}
else
{
fp1_t.write((char *) &p1,sizeof(struct product));
}
}
while(!fp2.eof())
{
fp2.read((char *) &p1,sizeof(struct product));
if(fp2.fail())
{
break;
}
else
{
fp2_t.write((char *) &p1,sizeof(struct product));
}
}
while(!fp3.eof())
{
fp3.read((char *) &p1,sizeof(struct product));
if(fp3.fail())
{
break;
}
else
{
fp3_t.write((char *) &p1,sizeof(struct product));
}
}
fp1_t.close();
fp2_t.close();
fp3_t.close();
}
fp1.close();
fp2.close();
fp3.close();
cout<<line;
cout<<"ntBackup Created Successfully...";
}
cout<<line<<conti;
getch();
}
我想知道,有没有比我正在做的更有效的方法来C++中创建文件夹?
当然,还有更多独立于平台的方法,以及更多类型安全的方法。尝试提升文件系统。
如果您使用的是Windows,那么CreateDirectory
是最简单的选择。下面是一个示例:
#include "Windows.h"
...
CreateDirectory("C:\temp\sampledir", NULL);
...
它是 Windows API 的一部分,记录在这里:CreateDirectory 函数的 MSDN 条目
我总是使用以下函数来创建文件夹。我使用它是因为,一方面,我不想使用任何像 boost
这样的第 3 方库;同时,简单地调用 WIN32 API CreateDirectory()
不够智能,这让我们可以创建一个目录,但它仅在父目录已经存在时才有效。此函数克服了此限制。例如,它可以通过传入"./subfolder/test"来创建一个名为 test
的文件夹,即使文件夹subfolder
不存在。此外,如果文件夹已存在,则不受影响,但如果不存在,则会创建该文件夹。
void create_directory(char* Path)
{
char DirName[256];
char* p = Path;
char* q = DirName;
while(*p)
{
if (('' == *p) || ('/' == *p))
{
if (':' != *(p-1))
{
CreateDirectory(DirName, NULL);
}
}
*q++ = *p++;
*q = ' ';
}
CreateDirectory(DirName, NULL);
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息