写入多个文件时崩溃

Crash while writing to multiple files

本文关键字:崩溃 文件      更新时间:2023-10-16

在用Java编程时,经过长时间的休息,我又开始使用C++了。我正在尝试将我的数据处理工作转换为C++。我在尝试同时打开和写入100多个文件时遇到了一个问题(按日期将10GB的文本文件拆分为多个文件)。同样,我只使用C++大约两天了,所以我已经满了。我的代码充满了其他问题,但我已经创建了最简单的片段来显示这个问题。

  • 我可以将files_to_open更改为任何数字,而且我没有任何问题
  • 如果files_to_write为<=125它运行文件
  • 如果files_to_write大于125,它就会崩溃

是什么原因造成的?

#include <map>  
#include <sstream>  
int main() {  
  std::map<int, FILE*> files;  
  int files_to_open = 200;  
  int files_to_write = 200;  
  // Open a set of files.  
  for(int i = 0; i < files_to_open; i++) {  
    std::ostringstream file_path;  
    file_path << "E:\tmp\file_" << i << ".txt";  
    files[i] = fopen(file_path.str().c_str(), "w");  
  }  
  // Write data to files.  
  for(int i = 0; i < files_to_write; i++) {  
    printf("%dn", i);  
    fwrite("Some Data", sizeof(char), 9, files[i]);  
  }  
  // Close files.  
  for (auto& file : files) {  
    fclose(file.second);  
  }  
  // End it all.  
  printf("Press Any Key to Continuen");  
  getchar();  
  return 0;  
}  

我假设fopen在files_to_write大于125时返回NULL。您的操作系统对每个进程可以打开的文件句柄数量有限制,您可能已经达到了限制。

125是完全合理的,因为您已经有0(stdin)、1(stdout)和2(stderr),所以再加125就是128,这是一个很好的限制。

无论哪种方式,在盲目写入FILE* 之前,都应该检查fopen的返回值