如何以更有效的方式在 c++ 中创建文件夹

How to create a folder in c++ in a more efficient way?

本文关键字:c++ 创建 文件夹 方式 有效      更新时间:2023-10-16

在我的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);
}