c++ - C/C++ 系统可移植方式更改最大打开文件数

标签 c++ file-io matrix operating-system temporary-files

我有一个 C++ 程序可以转置一个非常大的矩阵。矩阵太大,无法保存在内存中,所以我将每一列写入一个单独的临时文件,然后在处理完整个矩阵后连接临时文件。但是,我现在发现我遇到了打开的临时文件太多的问题(即操作系统不允许我打开足够的临时文件)。是否有系统可移植的方法来检查(并希望更改)允许打开文件的最大数量?

我意识到我可以关闭每个临时文件并仅在需要时重新打开,但我担心这样做会对性能产生影响。

我的代码工作如下(伪代码 - 不保证工作):

int Ncol=5000; // For example - could be much bigger.
int Nrow=50000; // For example - in reality much bigger.

// Stage 1 - create temp files
vector<ofstream *> tmp_files(Ncol);  // Vector of temp file pointers.
vector<string> tmp_filenames(Ncol);  // Vector of temp file names.
for (unsigned int ui=0; ui<Ncol; ui++)
{
    string filename(tmpnam(NULL));  // Get temp filename.
    ofstream *tmp_file = new ofstream(filename.c_str());
    if (!tmp_file->good())
         error("Could not open temp file.\n"); // Call error function
    (*tmp_file) << "Column" << ui;
    tmp_files[ui] = tmp_file;
    tmp_filenames[ui] = filename;
 }

 // Stage 2 - read input file and write each column to temp file
 ifstream input_file(input_filename.c_str());
 for (unsigned int s=0; s<Nrow; s++)
 {
       int input_num;
       ofstream *tmp_file;
       for (unsigned int ui=0; ui<Ncol; ui++)
       {
           input_file >> input_num;
           tmp_file = tmp_files[ui];          // Get temp file pointer
           (*tmp_file) << "\t" << input_num;  // Write entry to temp file.
       }
 }
 input_file.close();

 // Stage 3 - concatenate temp files into output file and clean up.
 ofstream output_file("out.txt");
 for (unsigned int ui=0; ui<Ncol; ui++)
 {
      string tmp_line;
      // Close temp file
      ofstream *tmp_file = tmp_files[ui];
      (*tmp_file) << endl;
      tmp_file->close();

      // Read from temp file and write to output file.
      ifstream read_file(tmp_filenames[ui].c_str());
      if (!read_file.good())
            error("Could not open tmp file for reading."); // Call error function
      getline(read_file, tmp_line);
      output_file << tmp_line << endl;
      read_file.close();

      // Delete temp file.
      remove(tmp_filenames[ui].c_str());
 }
 output_file.close();

非常感谢!

亚当

最佳答案

至少有两个限制:

  • 操作系统可能会施加限制;在 Unix(sh、bash 和类似的 shell)中,使用 ulimit 在系统管理员允许的范围内更改限制
  • C 库实现也可能有限制;你可能需要重新编译库来改变它

更好的解决方案是避免打开太多文件。在我自己的一个程序中,我围绕文件抽象编写了一个包装器(这是在 Python 中,但原理在 C 中是相同的),它跟踪每个文件中的当前文件位置,并根据需要打开/关闭文件,保留当前打开文件的池。

关于c++ - C/C++ 系统可移植方式更改最大打开文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6059919/

相关文章:

Python:长度计算矩阵与数组

linux - 如何从 Haskell 为所有用户设置文件权限

java - 如何输出\n?

r - 为什么 R 在使用 read.csv() 时会占用这么多内存?

c++ - 将 Matlab 中的以下 Matrix 代码转换为 C++ 中的 Eigen 的问题

java - 在 Java 中查找复杂矩阵的 SVD 矩阵

c++ - 为什么将 return 移动到函数末尾效率较低?

c++ - RcppArmadillo 中稀疏和密集矩阵的模板函数

c++ - 如何方便地打印出 std::stack 或 std::queue 中的所有元素

c++ - 如何定义一个地址为空的对象?