【问题标题】:How to read files from a folder in C++?如何从 C++ 中的文件夹中读取文件?
【发布时间】:2013-05-27 10:26:03
【问题描述】:

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

【问题讨论】:

  • 尝试 sdk 中的 findfirstfile 和 findnextfile 或 mfc 中的 cfilefind。
  • for (int i = 1; i <= 40; i++) { ... } 开头怎么样?然后阅读std::istringstream
  • 查看此问题的答案以了解如何使用 Win32 API 进行操作:stackoverflow.com/questions/15068475/…
  • 是关于如何为固定文件名生成字符串的问题,还是关于如何读取目录内容的问题?
  • 这是关于如何读取目录内容,在我的例子中,它们是“.jpg”文件。我想我已经通过在 Visual Studio 中使用“sprintf_s”功能解决了这个问题。谢谢大家。

标签: c++ visual-studio-2010 io


【解决方案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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2015-12-10
    • 1970-01-01
    • 2022-01-08
    • 2012-11-27
    相关资源
    最近更新 更多