gpt4 book ai didi

c++ - 挥之不去的打开文件导致 "Too many open files"

转载 作者:行者123 更新时间:2023-11-30 02:06:12 28 4
gpt4 key购买 nike

我有使用 boost 的代码来列出目录内容、遍历每个文件并进行一些数据处理。结果被打印到输出文件('histFile')。处理完约 2555 个文件后,出现错误:

boost::filesystem::directory_iterator::construct: Too many open files: "/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
}

如果我注释掉上面的最后两行(“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;
}

我是不是对指针/引用做错了什么?非常感谢任何帮助!

最佳答案

当您测试文件是否已经存在时,您在这段代码中泄漏了一个句柄:

// 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; }
}

是否真的有进行该检查的理由?如果文件不存在,为什么不让其创建呢?

关于c++ - 挥之不去的打开文件导致 "Too many open files",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8983792/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com