gpt4 book ai didi

c++ - 如何从 C++ 中的文件夹中读取文件?

转载 作者:太空狗 更新时间:2023-10-29 23:06:10 26 4
gpt4 key购买 nike

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

最佳答案

根据您的评论,我意识到您已经使用 _sprintf_s 提出了一个可行的解决方案.微软喜欢将其作为 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;
}
}

关于c++ - 如何从 C++ 中的文件夹中读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com