我如何知道FileInputStream是否打开了一个文件?

问题描述 投票:0回答:1

我正在使用 Poco::FileInputStream 设计一个复制功能

void do_copy_file(Poco::FileInputStream & iss)
{
    Poco::FileOutputStream fos("output.txt");

    Poco::StreamCopier::copyStream(iss, fos);
}

然后,用户可以调用 do_copy_file 这样

Poco::FileInputStream fis;
do_copy_file(fis);

我的问题是 我可以判断是否 指一个有效的文件?

poco-libraries
1个回答
1
投票

Poco::FileOutputStream 只是在试图打开它时发生错误时抛出一个Poco::FileException,例如使用了无效的文件路径。它没有任何功能来测试它是否有效。

你可以做的是改变你的 do_copy_file() 函数来捕获Poco::FileException异常,并返回一个布尔值--如果成功打开则为true,否则为false。

bool do_copy_file(Poco::FileInputStream & iss)
{
    bool result(true);

    try
    {
        Poco::FileOutputStream fos("output.txt");
        Poco::StreamCopier::copyStream(iss, fos);
    }
    catch (const Poco::FileException&)
    {
        result = false;
    }

    return result;
}

然后你可以像这样调用它。

Poco::FileInputStream fis;
if (do_copy_file(fis)
{
    //output file stream opened successfully
}

如果你想 do_copy_file() 来捕获打开输入流的异常,我建议在函数本身中这样做。不要传递输入流,而是传递文件路径。

bool do_copy_file(const std::string &inputFile, const std::string& outputFile)
{
    bool result(true);

    try
    {
        Poco::FileInputStream fis(inputFile);
        Poco::FileOutputStream fos(outputFile);
        Poco::StreamCopier::copyStream(fis, fos);
    }
    catch (const Poco::FileException&)
    {
        result = false;
    }

    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.