How to Compress Files to a Zip Archive using C/C++
When we want to share a high volume of files at once, creating a Zip archive is a necessity. Thankfully, using the ready-to-run C/C++ code examples below, we can build a zip archive API into our file processing/task management applications and take care this repetitive process programmatically.
The below code allows us to combine 10+ files (using multipart/form-data) into a single Zip archive. Before we structure our API call, let’s first install libcurl in our C/C++ project:
libcurl/7.75.0
After that, let’s copy the following examples into our file:
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, "https://api.cloudmersive.com/convert/archive/zip/create");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: multipart/form-data");
headers = curl_slist_append(headers, "Apikey: YOUR-API-KEY-HERE");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_mime *mime;
curl_mimepart *part;
mime = curl_mime_init(curl);
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile1");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile2");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile3");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile4");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile5");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile6");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile7");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile8");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile9");
curl_mime_filedata(part, "/path/to/file");
part = curl_mime_addpart(mime);
curl_mime_name(part, "inputFile10");
curl_mime_filedata(part, "/path/to/file");
curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);
res = curl_easy_perform(curl);
curl_mime_free(mime);
}
curl_easy_cleanup(curl);
We can now authenticate our request with a free-tier API key (we can get one by registering a free account on the Cloudmersive website) and perform this operation up to 800 times per month with no commitment.
Nice and easy!