徘徊打开的文件导致“打开的文件太多”

时间:2012-01-24 08:21:30

标签: c++ file boost

我有代码使用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
}

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

指针/引用我做错了吗? 任何帮助非常感谢!

1 个答案:

答案 0 :(得分:4)

当您测试文件是否存在时,您正在泄漏此代码中的句柄:

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

真的有理由进行检查吗?为什么不在文件尚不存在的情况下创建文件?