2016-07-28 7 views
1

特定の名前のファイルを作成したいとします。すでに存在している場合は、別のファイル名をいくつか追加したいと思う。 たとえば、ファイルlog.txtを作成したいのですが、すでに存在しています。次に、私は新しいファイルを作成しますlog1.txtlog2.txtlog3.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

関連する問題