2012-01-24 164 views
1

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

我做錯了指針/引用? 任何幫助非常感謝!

+3

你是說你發佈的代碼顯示問題?我沒有看到任何提升,那麼boost :: filesystem與這個問題有什麼關係? –

+0

您可能需要顯示'initFile'的其餘部分 - 我懷疑它是拋出一個異常,然後泄漏打開的文件。 –

+0

@Paur R:如果它拋出一個異常,那麼循環的其餘部分將不會被執行。所以那不可能。 – TonyK

回答

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

真的有什麼理由作出這樣的檢查?爲什麼不只是讓文件被創建,如果它不存在?

+0

謝謝!而已。沒有「真正的」原因;只是清潔。 – DilithiumMatrix