我有使用 boost 列出目录内容、迭代每个文件并执行一些数据处理操作的代码。结果被打印到输出文件('histFile')。处理完约 2555 个文件后,我收到错误:
boost::filesystem::directory_iterator::construct:打开的文件太多:“/Users/.../.../.../directory_with_files”
我的代码是:
for(int i = 0; i < 10000; i++) {
FILE *histFile;
string outputFileName = "somename";
bool ifRet = initFile(histFile, outputFileName.c_str(), "a"); // 1
fclose(histFile); // 2
}
Run Code Online (Sandbox Code Playgroud)
如果我注释掉上面的最后两行(“1”和“2”),代码就会正常完成。因此,“histFile”的副本似乎保持打开状态,但我不明白如何!这是该方法的操作部分:
bool initFile(FILE *&ofFile, const char *fileName, const char *openType, int overwriteOption) {
if(overwriteOption < 0 || overwriteOption > 2) {
fprintf(stderr, "ERROR: ToolBox - initFile() : unknown 'overwriteOption' (%d), setting to (0)!\n", overwriteOption);
}
// Read-Only
if(openType == "r") {
if(ofFile = fopen(fileName, "r")) { return true; }
fprintf(stderr, "ERROR: Could not open file (%s)!\n", fileName);
return false;
}
// Appending:
if(openType == "a" || openType == "a+") {
// Check if file already exists
if(!fopen(fileName, "r")){
fprintf(stderr, "ERROR: (%s) File does not Exist, cannot append!\n", fileName);
return false;
}
if(ofFile = fopen(fileName, openType)) { return true; }
}
// Writing:
// if file already exists
if(FILE *temp = fopen(fileName, "r")){
if(overwriteOption == 2) {
fprintf(stderr, "ERROR: (%s) File Exists!\n", fileName);
return false;
}
if(overwriteOption == 1) {
}
if(overwriteOption == 0) {
char backupFileName[TB_CHARLIMIT], backupPrefix[TB_CHARLIMIT];
strcpy(backupFileName, fileName); // copy filename
// create a prefix w/ format '<YYYYMMDD>BACKUP_'
DateTime now;
sprintf(backupPrefix, "%s", now.getDateStr().c_str());
strcat(backupPrefix, "BACKUP_");
// add to copied filename, and move file
strcpy(backupFileName, prependFileName(backupFileName, backupPrefix));
moveFile(fileName, backupFileName);
}
fclose(temp);
}
if(ofFile = fopen(fileName, openType)) { return true; }
// Default: Return error and false
fprintf(stderr, "ERROR: Could not open file (%s)!\n", fileName);
return false;
}
Run Code Online (Sandbox Code Playgroud)
我在指针/引用方面做错了什么吗?非常感谢任何帮助!
当您测试文件是否已存在时,您在这段代码中泄漏了句柄:
// Appending:
if(openType == "a" || openType == "a+") {
// Check if file already exists
if(!fopen(fileName, "r")){ // <-- the FILE* opened here is leaked
fprintf(stderr, "ERROR: (%s) File does not Exist, cannot append!\n", fileName);
return false;
}
if(ofFile = fopen(fileName, openType)) { return true; }
}
Run Code Online (Sandbox Code Playgroud)
真的有理由进行这项检查吗?如果文件尚不存在,为什么不直接创建它呢?