我有一个C++程序,转置一个非常大的矩阵。该矩阵太大而无法保存在内存中,因此我将每列写入一个单独的临时文件,然后在整个矩阵处理完成后连接临时文件。但是,现在我发现我遇到了打开太多临时文件的问题(即操作系统不允许我打开足够的临时文件)。是否有一个系统可移植的方法来检查(并希望更改)允许的最大数量的打开文件?C/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();
提前非常感谢!
亚当
便携式系统在Windows <-> * nix的便携感?不要以为你可以在Windows上设置这个参数。 – RedX 2011-05-19 14:06:59
如果您将这些数字存储为文本,那么您将会以所有从文本到数值的转换来惩罚您的表现。 – Andrew 2011-05-19 15:10:19
我正在阅读的格式是一种标准化生物信息学格式,其中列可以实际包含各种数字,文本字符串等。不幸的是,从文本到数字的转换是不可避免的。 (有问题的格式在这里:http://www.1000genomes.org/wiki/Analysis/Variant%20Call%20Format/vcf-variant-call-format-version-41) – Adam 2011-05-19 15:15:16