使用C++编写文件和目录

Col*_*mbo 1 c++ ofstream mkdir

我正在开发一个程序,它创建2000个目录并在每个目录中放入一个文件(只有10KB左右的文件).我正在使用mkdir制作dirs和ofstream(我也试过fopen)将文件写入固态驱动器(我正在进行速度测试以进行比较).

当我运行代码时,目录创建正常但文件在写入1000左右后停止写入.我尝试在每次写入之前设置一个延迟,以防它出现某种过载,并尝试使用fopen代替ofstream,但它总是停止在第1000个文件标记周围写入文件.

这是写入文件和退出的代码,告诉我它失败了哪个文件.

fsWriteFiles.open(path, ios::app); 
if(!fsWriteFiles.is_open()) 
{
   cout << "Fail at point: " << filecount  << endl; 
   return 1;
}
fsWriteFiles << filecontent;
fsWriteFiles.close();
Run Code Online (Sandbox Code Playgroud)

有没有人有这方面的经验或有任何理论?

这是完整的代码:此代码从随机数创建一个2位十六进制目录,然后从随机数创建一个4位十六进制目录,然后将文件存储在该目录中.在写完1000个文件后,它以"失败点"(我已经添加了一个cout)退出.这表示它无法创建文件,但它应该已经检查过该文件不存在.有时它从0开始失败,从底线击中第二个(文件已存在的else子句).任何帮助赞赏,我觉得这是与我正在尝试创建已经存在的文件,但我的文件存在检查已经不知何故滑落.有没有办法为失败的文件创建尝试获取错误消息?

int main()
{
  char charpart1[3] = "";
  char charpart3[5] = "";

  char path[35] = "";
  int randomStore = 0;

  //Initialize random seed
  srand(time(NULL));
  struct stat buffer ;

  //Create output file streams
  ofstream fsWriteFiles;    
  ifstream checkforfile;

  //Loop X times
  int dircount = 0;
  while(dircount < 2000)
  {
    path[0] = '\0'; //reset the char array that holds the path

    randomStore = rand() % 255;
    sprintf(charpart1, "%.2x", randomStore);
    randomStore = rand() % 65535;
    sprintf(charpart3, "%.4x", randomStore);

    //Check if top level dir exists, create if not
    strcat(path, "fastdirs/");
    strcat(path, charpart1);
    DIR *pdir=opendir(path);

    //If the dir does not exist create it with read/write/search permissions for owner 
    // and group, and with read/search permissions for others
    if(!pdir)
      mkdir(path,  S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

    //Check if 3rd level dir exists, create if not
    strcat(path, "/");
    strcat(path, charpart3);
    DIR *pdir3=opendir(path);

    if(!pdir3)
      mkdir(path,  S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

    strcat(path, "/");
    strcat(path, charpart3);
    strcat(path, ".txt");
    //Write the file if it does not already exist
    checkforfile.open(path, fstream::in);

    if (checkforfile.is_open() != true)
    {
      fsWriteFiles.open(path, ios::app); 
      if(!fsWriteFiles.is_open()) 
      {
        cout << "Fail at point: " << dircount << "\n" << endl;
        return 1;
      }
      fsWriteFiles << "test";
      fsWriteFiles.flush();
      fsWriteFiles.close();

      dircount ++; //increment the file counter
    }
    else
    {
      cout << "ex";
      checkforfile.close();
    }
  } 
}
Run Code Online (Sandbox Code Playgroud)

小智 6

你用opendir()打开目录,但从不用closedir()关闭它们 - 我怀疑那里也有资源限制.