异常处理 - 使用另一个文件名写入文件(如果该文件与原始文件名一起存在)

exception handling - writing file with another filename if it's exists with the original

本文关键字:文件名 文件 原始 一起 存在 如果 另一个 异常处理      更新时间:2023-10-16

当我试图通过在文件名中添加加号ID来编写已经存在的文件时,我会尝试处理这些情况。简而言之,它就像Windows在我复制文件时所做的那样。

假设我有一个文件test.bmp。我想对它应用一个过滤器,并将过滤后的图像保存为testout.bmp.但该文件夹中已经存在test out.bmp,因此程序会捕获它并将其保存为testout(1).bmp

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 */;
    }
};

目前,如果文件已经存在,则我的程序只存在(当文件夹中有同名文件时,file_exists仅返回true)。

我开始用异常处理重新设计我的基本函数,而不是简单地在出现任何错误时返回false。我在这里写了任何,因为我会有更多的抛出(如果文件无法打开或存在,但与我的文件等相同)。

我如何尝试捕获文件名,直到找到正确的文件名。或者有没有更简单的方法,我不应该使用异常?处理这个问题的最佳设计是什么?

我不太明白为什么要对此使用异常。除了一些非常具体的习惯用法之外,流控制之类的异常被认为是非常糟糕的风格。抛出和捕获任何不是从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;
}