【发布时间】:2021-08-30 00:19:26
【问题描述】:
我想使用 URLDownloadToFile 函数下载文件,我成功下载了 a 文件,文件名是预先起草的,例如 test.jpg。但是我无法将两个或更多文件下载到特定文件夹(因为这次你不能为两张或更多图片命名)。那么,有人可以帮忙吗? 对了,接下来是我的Test.cpp代码:
// Test.cpp : Defines the entry point for the application.
//
#include <Windows.h>
#include <thread>
#include <string>
#include <vector>
#include <Urlmon.h> //for URLDownloadToFile
#pragma comment(lib, "urlmon.lib")
#include <iostream>
void win_downLoad(std::vector<std::string>& urlVector )
{
std::string downloadURL = "";
int length = urlVector.size();
for (int i = 0; i < length; i++)
{
downloadURL = urlVector[i];
std::string savepath = "C:\\tmp\\" ;
URLDownloadToFile(NULL, downloadURL.c_str(), savepath.c_str(), 0, NULL);
}
}
int main()
{
std::vector<std::string> urlVector {"https://unsplash.com/photos/aoiUPcoLbBk/download?force=true", "https://unsplash.com/photos/0qGnW6iakaE/download?force=true",
"https://unsplash.com/photos/fWDe78O7-Ks/download?force=true", "https://unsplash.com/photos/4c5Fovle5Dc/download?force=true"};
const int num_threads = 4;
std::thread threads[num_threads];
for (size_t i = 0; i < num_threads; i++)
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
threads[i] = std::thread(win_downLoad, urlVector);
}
for (size_t i = 0; i < num_threads; i++)
{
if (threads[i].joinable())
{
threads[i].join();
}
}
std::cout << num_threads << " threads have been worked successfully.\n";
return 0;
}
所以,我的问题的本质是,如何使用 C++ 代码进行多线程 Win10操作系统下将多个文件下载到指定目录?
【问题讨论】:
-
你不能为每个图像生成一个不同的文件名吗?例如。
test1.jpg、test2.jpg等等。我没能完全理解困难的本质。 -
因为我想用多线程下载图片,所以无法为每张图片生成一个不同的文件名。如果将我的下载代码从
std::string savepath = "C:\\tmp\\"更改为std::string savepath = "C:\\tmp\\test.jpg" + i,它将无法正常工作。 -
你知道每个线程要下载多少张图片。只需将一个整数传递给每个线程以开始编号,并排列这些起始编号,使它们不重叠。例如。线程 1 从 1 开始编号;如果给定了 10 张图片要下载,则线程 2 从 11 开始编号。
-
谢谢!你的评论启发了我。让我再看看。@IgorTandetnik
-
是的,你说的情况我已经知道了。所以我现在无事可做。@Ron