2016-07-28 40 views
1

我想創建具有特定名稱的文件。如果它已經存在,那麼我想創建另一個文件,其名稱附加了一些數字。 例如,我想創建文件log.txt,但它已經在那裏。然後我將創建新文件log1.txt,log2.txt,log3.txt ....

有沒有什麼好的方法來記錄到文件重複信息中?提取文件重複信息

+0

爲什麼你不想測試文件的存在?例如,通過調用'stat()'。 – GMichael

+0

哦,謝謝!!!!!!!! – hellowl

回答

1

,只是檢查文件是否存在,如果是,在這段代碼檢查了下等,如:

#include <sys/stat.h> 
#include <iostream> 
#include <fstream> 
#include <string> 

/** 
* Check if a file exists 
* @return true if and only if the file exists, false else 
*/ 
bool fileExists(const std::string& file) { 
    struct stat buf; 
    return (stat(file.c_str(), &buf) == 0); 
} 

int main() { 
     // Base name for our file 
     std::string filename = "log.txt"; 
     // If the file exists...     
     if(fileExists(filename)) { 
       int i = 1; 
       // construct the next filename 
       filename = "log" + std::to_string(i) + ".txt"; 
       // and check again, 
       // until you find a filename that doesn't exist 
       while (fileExists(filename)) { 
         filename = "log" + std::to_string(++i) + ".txt"; 
       } 
     } 
     // 'filename' now holds a name for a file that 
     // does not exist 

     // open the file 
     std::ofstream outfile(filename); 
     // write 'foo' inside the file 
     outfile << "foo\n"; 
     // close the file 
     outfile.close(); 

     return 0; 
} 

它會找到一個非取的名字,並創建一個文件使用該名稱,寫入'foo'到最後,然後關閉文件。


我受到here的代碼的啓發。

+0

哦,謝謝你的闡述答案。謝謝!! – hellowl