用處

當我們完成一支程式發布出去時,我們可能會希望後續還能夠控制這支程式。例如使程式失效、更新等等…,這時我們就可以透過下載檔案並讀取檔案內容,再根據讀取到的內容做出對應的操作。

實現方法

需要引入以下的頭文件:

1
2
3
4
#include <tchar.h>
#include <urlmon.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "ws2_32.lib")

只需使用一行 code 即可:

1
HRESULT hr = URLDownloadToFile(NULL, _T("檔案下載路徑"), _T("檔案儲存路徑"), 0, NULL);

簡單實作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <tchar.h>
#include <urlmon.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "ws2_32.lib")

using namespace std;

int main()
{
char test[20];

cout << "Downloading file..." << endl;
HRESULT hr = URLDownloadToFile(NULL, _T("https://www.larrysprognotes.com/DownloadTest.dat"), _T("DownloadTest.dat"), 0, NULL);
cout << "Done!" << endl << endl;

ifstream in("DownloadTest.dat", ios::binary);

while (in.read((char*)&test, sizeof(test)))
cout << test;
cout << endl;
}

參考資料

C/C++ 簡易檔案下載