提取到文件的重复信息

Extract to file duplicate information

本文关键字:信息 文件 提取      更新时间:2023-10-16

我想创建具有特定名称的文件。如果它已经存在,那么我想创建另一个文件,名称后面加上一些数字。例如,我想创建文件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 << "foon";
        // close the file
        outfile.close();
        return 0;
}

它将找到一个未取的名称并创建一个具有该名称的文件,将"foo"写入其中,然后最终关闭该文件。


我从这里得到了代码的灵感。