异常处理 - 使用另一个文件名写入文件(如果该文件与原始文件名一起存在)
exception handling - writing file with another filename if it's exists with the original
当我试图通过在文件名中添加加号ID来编写已经存在的文件时,我会尝试处理这些情况。简而言之,它就像Windows在我复制文件时所做的那样。
假设我有一个文件test.bmp。我想对它应用一个过滤器,并将过滤后的图像保存为testout.bmp.但该文件夹中已经存在test out.bmp,因此程序会捕获它并将其保存为testout(1).bmp 目前,如果文件已经存在,则我的程序只存在(当文件夹中有同名文件时,file_exists仅返回true)。 我开始用异常处理重新设计我的基本函数,而不是简单地在出现任何错误时返回false。我在这里写了任何,因为我会有更多的抛出(如果文件无法打开或存在,但与我的文件等相同)。 我如何尝试和捕获文件名,直到找到正确的文件名。或者有没有更简单的方法,我不应该使用异常?处理这个问题的最佳设计是什么?bool IMAGE_DATA::openFile(const char* filename)
{
int i = 0;
try
{
if(file_exists(filename)) throw whatever;
}
catch(type whatever)
{
changefilename(filename,i)
i++;
if(file_exists(filename)) /* throw whatever/do something */;
}
};
我不太明白为什么要对此使用异常。除了一些非常具体的习惯用法之外,流控制之类的异常被认为是非常糟糕的风格。抛出和捕获任何不是从std::exception派生的东西也是不允许的。另外,您发布的代码甚至还没有接近编译,所以我的答案也是伪代码。还有一件事,为什么使用char*作为名称而不是std::string?
这能满足你的要求吗?
bool IMAGE_DATA::openFile(std::string filename)
{
while(file_exists(filename))
{
filename = add_1_to_filename(filename);
}
open(filename);
}
在您的场景中,拥有一个现有文件也不例外。因此,不要使用它们。如果你试图传递额外的信息,你可以使用函数:
#include <iostream>
struct FileExits {
bool value;
std::string information;
FileExits(const std::string& name)
: value(true), information("Test")
{}
operator bool () const { return value; }
};
int main() {
// Endless loop in this example
std::string name;
while(FileExits result = name) {
std::cout << result.information << std::endl;
}
// ...
return 0;
}
- 不带预处理器的调用方法/文件的文件名/行号
- 如何在目录及其子文件夹中构建文件名字符串向量?
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 生成文件文件名参数
- 如何让我的代码显示文件名不正确或文件中数字的平均值?
- 如何更改目录中文件夹中的文件名
- 从 C++ 中的文件路径中提取文件名
- 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex
- 如何更改变量文件名的文件路径?
- 有没有办法打印包含当前文件的文件的文件名
- CMake 意外地将最后一个文件名预置到可执行文件中
- Qt - 如何在 30 天后删除日志文件,文件名不固定
- 将文件重命名为已存在的文件名
- 如何在 Windows 上从 C++11 统计信息对象的文件序列号中查找文件名
- Xcode 8.3.2 中的错误警告:文件的非可移植路径 - 指定的路径与磁盘上的文件名不同
- 如何在C 中读取具有前缀和时间戳为文件名的文件
- 使用文件名作为字符串从任意souce .cpp文件中调用函数
- 预处理器指令:为什么使用#Define的标题文件标识符与标头文件名不同
- 如何通过键入文件名来获取文件的目录。(C++)
- 如何根据用户输入指定的文件名打开文件