【问题标题】:Extract to file duplicate information提取以归档重复信息
【发布时间】:2016-07-28 04:36:17
【问题描述】:

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

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

【问题讨论】:

  • 你为什么不只是想测试文件是否存在?例如,通过调用stat()

标签: c++ file c++11 posix stat


【解决方案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 的代码启发了我。

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 2021-08-10
    • 2013-03-09
    • 2012-07-01
    • 1970-01-01
    相关资源
    最近更新 更多