提取到文件的重复信息
Extract to file duplicate information
我想创建具有特定名称的文件。如果它已经存在,那么我想创建另一个文件,名称后面加上一些数字。例如,我想创建文件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 << "foon";
// close the file
outfile.close();
return 0;
}
它将找到一个未取的名称并创建一个具有该名称的文件,将"foo"写入其中,然后最终关闭该文件。
我从这里得到了代码的灵感。
相关文章:
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 创建进行生产构建并创建调试信息的C++生成文件的最佳方法?
- 将对象信息保存到二进制文件中
- 错误 VSP1011:无法获取调试信息.与 /配置文件链接器开关链接
- Qt读取文本文件的一些信息
- 将文件信息(字符数组)嵌入到编译的二进制文件中
- 从带有 getline() 的文件读入一行上有多个信息得到无效参数错误
- 如何使用所有其他文件信息来编译代码,例如HAAR级联训练的权重的XML文件
- 是否可以将信息从XML文件转换为CPP
- 如何在文本文件中搜索员工记录(按名称)并仅显示其详细信息?
- 使用TDD时隐藏文件访问实现详细信息
- 生成有关编译的信息文件
- 如果我尝试将对话框从一个项目移动到另一个项目,我是否需要从 rc 文件中复制 DESIGNINFO、对话框信息和AFX_
- 在远程嵌入式设备上使用核心文件的 GDB - 如何获取有关回溯的更多信息?
- 接受多个输入(如 +、- 和平方数字)的计算器.从文本文件中提取信息
- 如何在 Windows 上从 C++11 统计信息对象的文件序列号中查找文件名
- 构建 vcxproj 文件给我一个无信息的错误"The system cannot find the path specified"
- 什么是阅读和将信息与此文本文件分开的好方法
- Fuse文件系统查找/Trash、/autorun.inf和/.xdg卷信息文件
- DWARF调试信息文件的diff工具