3

我想jpg使用 c++ 从文件夹中读取一些文件。我已经搜索了互联网,但找不到解决此问题的方法。我不想使用 Boost 或其他库,而只是用 C++ 函数编写它。例如,我的"01.jpg, 02.jpg,...40.jpg"文件夹中有 40 张图片,命名为 我尝试了几次,但都失败了。我正在使用 Visual Studio。有人可以帮我吗?谢谢你。

4

1 回答 1

1

根据您的评论,我意识到您已经提出了一个可行的解决方案,使用_sprintf_s. Microsoft 喜欢将其作为一种更安全的替代方案来推广sprintf,如果您使用 C 编写程序,这是正确的。但是在 C++ 中,有更安全的方法来构建不需要您管理缓冲区或了解以下内容的字符串它的最大尺寸。如果您想习惯使用它,我建议您放弃使用_sprintf_s并使用 C++ 标准库提供的工具。

下面介绍的解决方案使用一个简单的for循环std::stringstream来创建文件名并加载图像。我还包括使用std::unique_ptr生命周期管理和所有权语义。根据图像的使用方式,您可能需要std::shared_ptr改用。

#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <stdexcept>

// Just need something for example
struct Image
{
    Image(const std::string& filename) : filename_(filename) {}
    const std::string filename_;
};

std::unique_ptr<Image> LoadImage(const std::string& filename)
{
    return std::unique_ptr<Image>(new Image(filename));
}

void LoadImages(
    const std::string& path,
    const std::string& filespec,
    std::vector<std::unique_ptr<Image>>& images)
{
    for(int i = 1; i <= 40; i++)
    {
        std::stringstream filename;

        // Let's construct a pathname
        filename
            << path
            << "\\"
            << filespec
            << std::setfill('0')    // Prepends '0' for images 1-9
            << std::setw(2)         // We always want 2 digits
            << i
            << ".jpg";

        std::unique_ptr<Image> img(LoadImage(filename.str()));
        if(img == nullptr) {
            throw std::runtime_error("Unable to load image");
        }
        images.push_back(std::move(img));
    }
}

int main()
{
    std::vector<std::unique_ptr<Image>>    images;

    LoadImages("c:\\somedirectory\\anotherdirectory", "icon", images);

    // Just dump it
    for(auto it = images.begin(); it != images.end(); ++it)
    {
        std::cout << (*it)->filename_ << std::endl;
    }
}
于 2013-05-27T16:15:52.577 回答