1
我想创建具有特定名称的文件。如果它已经存在,那么我想创建另一个文件,其名称附加了一些数字。 例如,我想创建文件log.txt
,但它已经在那里。然后我将创建新文件log1.txt
,log2.txt
,log3.txt
....
有没有什么好的方法来记录到文件重复信息中?提取文件重复信息
我想创建具有特定名称的文件。如果它已经存在,那么我想创建另一个文件,其名称附加了一些数字。 例如,我想创建文件log.txt
,但它已经在那里。然后我将创建新文件log1.txt
,log2.txt
,log3.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的代码的启发。
哦,谢谢你的阐述答案。谢谢!! – hellowl
为什么你不想测试文件的存在?例如,通过调用'stat()'。 – GMichael
哦,谢谢!!!!!!!! – hellowl