提取文件重复信息

Extract to file duplicate information

我想创建具有特定名称的文件。如果它已经存在,那么我想创建另一个文件,其名称附加一些数字。 例如,我想创建文件 log.txt 但它已经存在。然后我将创建新文件log1.txtlog2.txtlog3.txt.....

有什么好的方法可以记录到文件中的重复信息吗?

只检查文件是否存在,如果存在,检查下一个文件,依此类推,如代码所示:

#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 的代码。