用 C++ 下载文件
本文介绍如何使用 C++ 下载文件。
用 C++ 下载文件
使用 C++ 下载文件是一项简单的操作,可以使用 win32 API URLDownloadToFile 来完成。 该 API 可以从给定的链接下载我们计算机中的文件。
我们可以根据需要将下载的项目保存为文件或字符串。 这两者都可以使用不同的操作来完成。
让我们从下载文件开始。
C++ 下载为文件
如上所述,我们可以使用win32 API URLDownloadToFile,我们可以从给定的链接下载任何文件。 该文件将保存在同一工作目录中。
让我们尝试一个例子。
#include <windows.h>
#include <cstdio>
#include<string>
#pragma comment(lib, "Urlmon.lib")
using namespace std;
int main() {
// the URL from where the file will be downloaded
string SourceURL = "https://picsum.photos/200/300.jpg";
// destination file
string DestinationFile = "DemoFile.jpg";
// URLDownloadToFile returns S_OK on success
if (S_OK == URLDownloadToFile(NULL, SourceURL.c_str(), DestinationFile.c_str(), 0, NULL)) {
printf("The file is successfully downloaded.");
return 0;
}
else {
printf("Download Failed");
return -1;
}
}
在编译上述代码之前,需要注意的是,上述代码仅适用于使用 Visual Studio Express、Visual C++ 或任何其他相关编译器的 NSVC 编译器。 它无法与 MinGW 编译器一起使用,因为它不包含 URLDownloadToFile API。
一旦我们运行上面的代码,它将从链接下载文件。
查看输出:
The file is successfully downloaded.
C++ 下载为字节串
此方法使用 win32 API URLOpenBlockingStream 将文件下载为字节字符串,也可以将其保存在文件中。 这是一个棘手的逐步过程; 请按照以下步骤操作。
- 首先,使用 URLOpenBlockingStream 获取 URL 的 IStream 接口。
- 然后插入 HTTP 和 HTTPS 协议都可以使用的 URL。
- 一旦 IStream 可用,请使用读取函数下载字节。 这里我们可能需要使用循环。
- 一旦字节被收集到字符串中,我们就可以将它们保存到文件中或下载字符串。
让我们尝试一个基于上述步骤的示例,并尝试以字节为单位获取 Google 主页。
#pragma comment(lib, "urlmon.lib")
#include <urlmon.h>
#include <cstdio>
#include <iostream>
#include <string>
#define getURL URLOpenBlockingStreamA
using namespace std;
int main() {
IStream* DemoStream;
const char* SourceURL = "http://google.com";
if (getURL(0, SourceURL, &DemoStream, 0, 0)) {
cout << "An Error has occured.";
cout << "Please Check the internet";
cout << "Please Check the source URL.";
return -1;
}
// this char array will be filled with bytes from the URL
char DemoBuff[100];
// keep appending the bytes to this string
string DemoStr;
unsigned long Bytes_Read;
while(true) {
DemoStream->Read(DemoBuff, 100, &Bytes_Read);
if(0U == Bytes_Read) {
break;
}
// appending and collecting to the string
DemoStr.append(DemoBuff, Bytes_Read);
};
DemoStream->Release();
cout << DemoStr << endl;
return 0;
}
上面的代码将以字节字符串形式获取 Google 主页; 虽然以字节串的形式下载东西效率不高,但我们也可以将字节保存在文件中供以后使用。 上述代码的输出将是一长串字节。
确保使用与第一个代码相同的编译器运行上述代码,因为 URLOpenBlockingStream 也不适用于 MinGW C++ 编译器。
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。