tencent cloud

Cloud Object Storage

Release Notes and Announcements
Release Notes
Announcements
Product Introduction
Overview
Features
Use Cases
Strengths
Concepts
Regions and Access Endpoints
Specifications and Limits
Service Regions and Service Providers
Billing
Billing Overview
Billing Method
Billable Items
Free Tier
Billing Examples
Viewing and Downloading Bill
Payment Overdue
FAQs
Getting Started
Console
Getting Started with COSBrowser
User Guide
Creating Request
Bucket
Object
Data Management
Batch Operation
Global Acceleration
Monitoring and Alarms
Operations Center
Data Processing
Content Moderation
Smart Toolbox
Data Processing Workflow
Application Integration
User Tools
Tool Overview
Installation and Configuration of Environment
COSBrowser
COSCLI (Beta)
COSCMD
COS Migration
FTP Server
Hadoop
COSDistCp
HDFS TO COS
GooseFS-Lite
Online Tools
Diagnostic Tool
Use Cases
Overview
Access Control and Permission Management
Performance Optimization
Accessing COS with AWS S3 SDK
Data Disaster Recovery and Backup
Domain Name Management Practice
Image Processing
Audio/Video Practices
Workflow
Direct Data Upload
Content Moderation
Data Security
Data Verification
Big Data Practice
COS Cost Optimization Solutions
Using COS in the Third-party Applications
Migration Guide
Migrating Local Data to COS
Migrating Data from Third-Party Cloud Storage Service to COS
Migrating Data from URL to COS
Migrating Data Within COS
Migrating Data Between HDFS and COS
Data Lake Storage
Cloud Native Datalake Storage
Metadata Accelerator
GooseFS
Data Processing
Data Processing Overview
Image Processing
Media Processing
Content Moderation
File Processing Service
File Preview
Troubleshooting
Obtaining RequestId
Slow Upload over Public Network
403 Error for COS Access
Resource Access Error
POST Object Common Exceptions
API Documentation
Introduction
Common Request Headers
Common Response Headers
Error Codes
Request Signature
Action List
Service APIs
Bucket APIs
Object APIs
Batch Operation APIs
Data Processing APIs
Job and Workflow
Content Moderation APIs
Cloud Antivirus API
SDK Documentation
SDK Overview
Preparations
Android SDK
C SDK
C++ SDK
.NET(C#) SDK
Flutter SDK
Go SDK
iOS SDK
Java SDK
JavaScript SDK
Node.js SDK
PHP SDK
Python SDK
React Native SDK
Mini Program SDK
Error Codes
Harmony SDK
Endpoint SDK Quality Optimization
Security and Compliance
Data Disaster Recovery
Data Security
Cloud Access Management
FAQs
Popular Questions
General
Billing
Domain Name Compliance Issues
Bucket Configuration
Domain Names and CDN
Object Operations
Logging and Monitoring
Permission Management
Data Processing
Data Security
Pre-signed URL Issues
SDKs
Tools
APIs
Agreements
Service Level Agreement
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary

Getting Started

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2025-12-29 16:35:31

Relevant Resources

Download address of XML C SDK source code for the cloud object storage: XML C SDK.
Download address of the Demo: XML C SDK Demo.
The SDK changelog is available at Changelog.
For SDK FAQ, see: C SDK FAQ.
Note:
If you encounter errors such as missing functions or methods when using the SDK, please upgrade to the latest version and try again.

Environment Configuration and Preparation

Dependency libraries: libcurl apr apr-util minixml.
COS C SDK supports the following operating systems and compiler environments: Linux, macOS, Windows.
You need to obtain a Tencent Cloud API key. This key is a prerequisite for your use of the various features of the COS SDK.

Installing the SDK

1. Install the CMake tool (version 2.6.0 or later is recommended). Click here to download. The installation procedure is as follows:
./configure
make
make install
2. Install libcurl (version 7.32.0 or later is recommended). Click here to download. The installation procedure is as follows:
./configure
make
make install
3. Install apr (version 1.5.2 or later is recommended). Click here to download. The installation procedure is as follows:
./configure
make
make install
4. Install apr-util (version 1.5.4 or later is recommended). Click here to download. During installation, specify the --with-apr option. The installation procedure is as follows:
./configure --with-apr=/your/apr/install/path
make
make install
5. Install minixml (version 2.8 - 2.12 is recommended). Click here to download. The installation procedure is as follows:
./configure
make
make install
6. Compile and install COS C SDK. Download XML C SDK source code, run the following command:
cmake .
make
make install
7. Set environment variables:
Take Linux as an example. The apr and apr-util libraries are installed by default at /usr/local/apr/lib, and their pkgconfig directory is at /usr/local/apr/lib/pkgconfig. The cos_c_sdk, curl, and mxml are installed by default at /usr/local/lib, and their pkgconfig directory is at /usr/local/lib/pkgconfig.
Edit the ~/.bashrc file and add the following environment variables:
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/local/apr/lib/pkgconfig
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/apr/lib
Run the following command to make the environment variables take effect:
. ~/.bashrc

Initialize COS Service

The following is the general process for using the XML C SDK.
1. Initialize SDK.
2. Set parameters of the request options. For the meanings and methods to obtain APPID, SecretId, SecretKey, Bucket, and other terms, see COS Terminology.
APPID is one of the account identifiers assigned by the system after applying for a Tencent Cloud account.
access_key_id and access_key_secret are API keys for the account.
endpoint is the domain information for COS access. For details, see the Regions and Access Domains documentation. For example, the endpoint for the Guangzhou region is cos.ap-guangzhou.myqcloud.com, and the endpoint for the global acceleration domain is cos.accelerate.myqcloud.com. You can prefix the endpoint with http or https. The SDK accesses COS via http by default. To access the Guangzhou region endpoint via https, use https://cos.ap-guangzhou.myqcloud.com.
is_cname indicates whether the endpoint is a custom domain name. If is_cname is set to 1, the endpoint represents a custom domain name.
3. Set parameters required for the API.
4. Call the SDK API to initiate a request and obtain the result of the request-response.

Initialization

Note:
It is recommended that users call the SDK using the sub-account key + environment variables approach to enhance security. When authorizing sub-accounts, follow the principle of least privilege to prevent leakage of resources beyond the target bucket or objects.
If you must use permanent secret keys, it is recommended that you follow the Principle of Least Privilege to restrict the scope of permissions for these keys.
int main(int argc, char *argv[])
{
/* Call the cos_http_io_initialize method at the program entry. This method will initialize some global resources involving network, memory, and so on.*/
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
exit(1);
}

/* Call the APIs of the COS SDK to upload or download files. */
/* ... Code for user logic is omitted here.*/

/* Before the program ends, call the cos_http_io_deinitialize method to release the previously allocated global resources.*/
cos_http_io_deinitialize();
return 0;
}

Initializing Request Options

Temporary Secret Key (Recommended)
Permanent Secret Key (Not Recommended)
Note:
Temporary secret key generation and usage can be found in Temporary Secret Key Generation and Usage Guidelines.
/* Equivalent to apr_pool_t, used for memory pool for memory management, achieving code in apr library.*/
cos_pool_t *pool;
cos_request_options_t *options;

/* Recreate a new memory pool, and the second parameter is NULL, indicating that it does not inherit from other memory pools.*/
cos_pool_create(&pool, NULL);

/* Create and initialize options, and this parameter mainly includes global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl parameters.
* The memory for options is allocated by the pool. After the pool is released later, the memory for options is effectively released as well, eliminating the need for separate memory deallocation.
*/
options = cos_request_options_create(pool);
options->config = cos_config_create(options->pool);

/* cos_str_set uses a char* string to initialize the cos_string_t type.*/
cos_str_set(&options->config->endpoint, "<YourEndpoint>"); //Fill in the Endpoint based on the COS service domain name corresponding to your region.
cos_str_set(&options->config->access_key_id, "<YourSecretId>"); //SecretId for temporary secret key, see Temporary Secret Key Generation and Usage Guidelines at https://www.tencentcloud.com/document/product/436/14048
cos_str_set(&options->config->access_key_secret, "<YourSecretKey>"); //SecretKey for temporary secret key, see Temporary Secret Key Generation and Usage Guidelines at https://www.tencentcloud.com/document/product/436/14048
cos_str_set(&options->config->sts_token, "<YourStsToken>"); //Token for temporary secret key, see Temporary Secret Key Generation and Usage Guidelines at https://www.tencentcloud.com/document/product/436/14048
cos_str_set(&options->config->appid, "<YourAppId>"); //Your AppId obtained after you register for the COS service.

/* Is CNAME used or not? */
options->config->is_cname = 0;
/* Use a custom domain name to access COS. */
/*
options->config->is_cname = 1;
cos_str_set(&options->config->endpoint, "<CustomDomain>");
*/

/* Used to set network-related parameters, such as timeout duration.*/
options->ctl = cos_http_controller_create(options->pool, 0);

/* Used to set whether to automatically add the Content-MD5 header to upload requests. When enable is COS_FALSE, the upload request will not automatically add the Content-MD5 header. When enable is COS_TRUE, the upload request will automatically add the Content-MD5 header. If this option is not set, the Content-MD5 header will be added by default. */
cos_set_content_md5_enable(options->ctl, COS_FALSE);

/* Used to set the address for request routing and port. Generally, you do not need to set this parameter. The request will be routed according to the result of domain resolution.*/
//cos_set_request_route(options->ctl, "192.168.12.34", 80);
/* Equivalent to apr_pool_t, used for memory pool for memory management, achieving code in apr library.*/
cos_pool_t *pool;
cos_request_options_t *options;

/* Recreate a new memory pool, and the second parameter is NULL, indicating that it does not inherit from other memory pools.*/
cos_pool_create(&pool, NULL);

/* Create and initialize options, and this parameter mainly includes global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl parameters.
/* The memory of options is allocated by the pool. After the pool is released, the memory of options is also released, so there is no need to release the memory separately. */
*/
options = cos_request_options_create(pool);
options->config = cos_config_create(options->pool);

/* cos_str_set uses a char* string to initialize the cos_string_t type.*/
cos_str_set(&options->config->endpoint, "<YourEndpoint>"); //Fill in the Endpoint based on the COS service domain name corresponding to your region.
cos_str_set(&options->config->access_key_id, "<YourSecretId>"); //Your SecretId. It is recommended to use a sub-account key and follow the principle of least privilege to minimize usage risks. For information on obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
cos_str_set(&options->config->access_key_secret, "<YourSecretKey>"); //Your SecretKey. It is recommended to use a sub-account key and follow the principle of least privilege to minimize usage risks. For information on obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
cos_str_set(&options->config->appid, "<YourAppId>"); //Your AppId obtained after registration for the COS service is performed.

/* Is CNAME used or not? */
options->config->is_cname = 0;
/* Use a custom domain name to access COS. */
/*
options->config->is_cname = 1;
cos_str_set(&options->config->endpoint, "<CustomDomain>");
*/

/* Used to set network-related parameters, such as timeout duration.*/
options->ctl = cos_http_controller_create(options->pool, 0);

/* Used to set whether to automatically add the Content-MD5 header to upload requests. When enable is COS_FALSE, the upload request will not automatically add the Content-MD5 header. When enable is COS_TRUE, the upload request will automatically add the Content-MD5 header. If this option is not set, the Content-MD5 header will be added by default. */
cos_set_content_md5_enable(options->ctl, COS_FALSE);

/* Used to set the address for request routing and port. Generally, you do not need to set this parameter. The request will be routed according to the result of domain resolution.*/
//cos_set_request_route(options->ctl, "192.168.12.34", 80);

Access the COS Service

Create a bucket
Querying the Bucket List
Querying the Object List
PUT Object
Downloading an Object
Deleting Objects
For the complete sample code, see: put_bucket_demo.c
// put_bucket_demo.c
#include <stdint.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include "cos_api.h"
#include "cos_http_io.h"
#include "cos_log.h"

/**
* This example demonstrates how to use the COS SDK for C to create a bucket.
*/

// Name of the COS bucket, in the format of [bucket]-[appid], such as examplebucket-1250000000. You can view it at https://console.tencentcloud.com/cos5/bucket
char bucket_name[] = "examplebucket-1250000000";
// A unique user-level resource identifier for developers accessing COS services, used to identify resources. It can be obtained on the https://console.tencentcloud.com/cam/capi page.
char appid[] = "1250000000";
// Project Identity ID/Key credentials for developers, which can be obtained on the https://console.tencentcloud.com/cam/capi page.
char secret_id[] = "xxxxxxxx";
char secret_key[] = "xxxxxxxxxxxx";
//endpoint is the domain information for accessing COS (without the bucket prefix, [bucket]-[appid] will be automatically prefixed when COS is accessed). For details, see the documentation at https://www.tencentcloud.com/document/product/436/6224.
char endpoint[] = "cos.ap-xxx.myqcloud.com";
// Whether to use a custom domain. If it is set to COS_TRUE, you need to modify the endpoint value to the custom domain when accessing COS.
int is_cname = COS_FALSE;

void init_test_config(cos_config_t* config, int is_cname) {
cos_str_set(&config->endpoint, endpoint);
cos_str_set(&config->access_key_id, secret_id);
cos_str_set(&config->access_key_secret, secret_key);
cos_str_set(&config->appid, appid);
// cos_str_set(&config->sts_token, token); // token used when a temporary key is used
config->is_cname = is_cname; // whether to use a custom domain
}

void init_test_request_options(cos_request_options_t* options, int is_cname) {
options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);
}

void log_status(cos_status_t* s) {
cos_warn_log("status->code: %d", s->code);
if (s->error_code)
cos_warn_log("status->error_code: %s", s->error_code);
if (s->error_msg)
cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id)
cos_warn_log("status->req_id: %s", s->req_id);
}

void put_bucket_demo() {
cos_pool_t *p = NULL;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_acl_e cos_acl = COS_ACL_PRIVATE;
cos_string_t bucket;
cos_table_t *resp_headers = NULL;

cos_pool_create(&p, NULL);
options = cos_request_options_create(p);
init_test_request_options(options, is_cname);
cos_str_set(&bucket, bucket_name);

//create test bucket
s = cos_create_bucket(options, &bucket, cos_acl, &resp_headers);
log_status(s);
cos_pool_destroy(p);
}

int main() {
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
exit(1);
}
// set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_ERROR);
put_bucket_demo();
// cos_http_io_deinitialize last
cos_http_io_deinitialize();
return 0;
}
For the complete sample code, see: get_bucket_list_demo.c
// get_bucket_list_demo.c
#include <stdint.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include "cos_api.h"
#include "cos_http_io.h"
#include "cos_log.h"

/**
* This example demonstrates how to use the COS SDK for C to obtain the bucket list.
*/

// A unique user-level resource identifier for developers accessing COS services, used to identify resources. It can be obtained on the https://console.tencentcloud.com/cam/capi page.
char appid[] = "1250000000";
// Project Identity ID/Key credentials for developers, which can be obtained on the https://console.tencentcloud.com/cam/capi page.
char secret_id[] = "xxxxxxxx";
char secret_key[] = "xxxxxxxxxxxx";
//endpoint is the domain information for accessing COS (without the bucket prefix, [bucket]-[appid] will be automatically prefixed when COS is accessed). For details, see the documentation at https://www.tencentcloud.com/document/product/436/6224.
char endpoint[] = "cos.ap-xxx.myqcloud.com";
// Whether to use a custom domain. If it is set to COS_TRUE, you need to modify the endpoint value to the custom domain when accessing COS.
int is_cname = COS_FALSE;

void init_test_config(cos_config_t* config, int is_cname) {
cos_str_set(&config->endpoint, endpoint);
cos_str_set(&config->access_key_id, secret_id);
cos_str_set(&config->access_key_secret, secret_key);
cos_str_set(&config->appid, appid);
// cos_str_set(&config->sts_token, token); // token used when a temporary key is used
config->is_cname = is_cname; // whether to use a custom domain
}

void init_test_request_options(cos_request_options_t* options, int is_cname) {
options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);
}

void log_status(cos_status_t* s) {
cos_warn_log("status->code: %d", s->code);
if (s->error_code)
cos_warn_log("status->error_code: %s", s->error_code);
if (s->error_msg)
cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id)
cos_warn_log("status->req_id: %s", s->req_id);
}
void get_bucket_list_demo() {
cos_pool_t *pool = NULL;
cos_status_t *status = NULL;
cos_request_options_t *options = NULL;
cos_get_service_params_t *list_params = NULL;
cos_table_t *resp_headers = NULL;

//Creating a memory pool
cos_pool_create(&pool, NULL);

//Initializing the request options
options = cos_request_options_create(pool);
options->config = cos_config_create(options->pool);

init_test_request_options(options, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);

//Creating parameters for get service, which retrieves all buckets by default
list_params = cos_create_get_service_params(options->pool);
//If all_region is set to 0, the query will only be performed based on the region of options->config->endpoint
//list_params->all_region = 0;

status = cos_get_service(options, list_params, &resp_headers);
log_status(status);
if (!cos_status_is_ok(status)) {
cos_pool_destroy(pool);
return;
}

// View the result
cos_get_service_content_t *content = NULL;
char *line = NULL;
cos_list_for_each_entry(cos_get_service_content_t, content, &list_params->bucket_list, node) {
line = apr_psprintf(options->pool, "%.*s\\t%.*s\\t%.*s\\n", content->bucket_name.len, content->bucket_name.data, content->location.len, content->location.data, content->creation_date.len, content->creation_date.data);
printf("%s", line);
}

cos_pool_destroy(pool);
}

int main() {
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
exit(1);
}
// set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_ERROR);
get_bucket_list_demo();
// cos_http_io_deinitialize last
cos_http_io_deinitialize();
return 0;
}
For the complete sample code, see: list_object_demo.c
// list_object_demo.c
#include <stdint.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include "cos_api.h"
#include "cos_http_io.h"
#include "cos_log.h"

/**
* This example demonstrates how to use the COS C SDK to list objects (list all objects in a bucket).
*/

// Name of the COS bucket, in the format of [bucket]-[appid], such as examplebucket-1250000000. You can view it at https://console.tencentcloud.com/cos5/bucket
char bucket_name[] = "examplebucket-1250000000";
// A unique user-level resource identifier for developers accessing COS services, used to identify resources. It can be obtained on the https://console.tencentcloud.com/cam/capi page.
char appid[] = "1250000000";
// Project Identity ID/Key credentials for developers, which can be obtained on the https://console.tencentcloud.com/cam/capi page.
char secret_id[] = "xxxxxxxx";
char secret_key[] = "xxxxxxxxxxxx";
//endpoint is the domain information for accessing COS (without the bucket prefix, [bucket]-[appid] will be automatically prefixed when COS is accessed). For details, see the documentation at https://www.tencentcloud.com/document/product/436/6224.
char endpoint[] = "cos.ap-xxx.myqcloud.com";
// Whether to use a custom domain. If it is set to COS_TRUE, you need to modify the endpoint value to the custom domain when accessing COS.
int is_cname = COS_FALSE;

void init_test_config(cos_config_t* config, int is_cname) {
cos_str_set(&config->endpoint, endpoint);
cos_str_set(&config->access_key_id, secret_id);
cos_str_set(&config->access_key_secret, secret_key);
cos_str_set(&config->appid, appid);
// cos_str_set(&config->sts_token, token); // token used when a temporary key is used
config->is_cname = is_cname; // whether to use a custom domain
}

void init_test_request_options(cos_request_options_t* options, int is_cname) {
options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);
}

void log_status(cos_status_t* s) {
cos_warn_log("status->code: %d", s->code);
if (s->error_code)
cos_warn_log("status->error_code: %s", s->error_code);
if (s->error_msg)
cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id)
cos_warn_log("status->req_id: %s", s->req_id);
}

void list_all_objects_demo() {
cos_pool_t* p = NULL;
cos_status_t* s = NULL;
cos_request_options_t* options = NULL;
cos_string_t bucket;
cos_table_t* resp_headers;
int is_truncated = 1;
cos_string_t marker;

cos_pool_create(&p, NULL);
options = cos_request_options_create(p);
init_test_request_options(options, is_cname);
cos_str_set(&bucket, bucket_name);

// list object (get bucket)
cos_list_object_params_t* list_params = NULL;
list_params = cos_create_list_object_params(p);
// Setting the maximum number of objects to be traversed, with a maximum number of 1000 objects supported by a listobject.
list_params->max_ret = 1000;
cos_str_set(&marker, "");
while (is_truncated) {
list_params->marker = marker;
cos_list_init(&list_params->object_list);
s = cos_list_object(options, &bucket, list_params, &resp_headers);
if (!cos_status_is_ok(s)) {
printf("list object failed, req_id:%s\\n", s->req_id);
break;
}
// list_params->object_list returns the listed object(s).
cos_list_object_content_t* content = NULL;
cos_list_for_each_entry(cos_list_object_content_t, content, &list_params->object_list, node) {
printf("object: %s\\n", content->key.data);
}

is_truncated = list_params->truncated;
marker = list_params->next_marker;
}
cos_pool_destroy(p);
}

int main() {
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
exit(1);
}
// set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);
list_all_objects_demo();
// cos_http_io_deinitialize last
cos_http_io_deinitialize();
return 0;
}
For the complete sample code, see: put_object_demo.c
// put_object_demo.c
#include <stdint.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include "cos_api.h"
#include "cos_http_io.h"
#include "cos_log.h"

/**
* This sample demonstrates how to use the COS SDK for C to perform object uploads (uploading local files).
*/

// Name of the COS bucket, in the format of [bucket]-[appid], such as examplebucket-1250000000. You can view it at https://console.tencentcloud.com/cos5/bucket
char bucket_name[] = "examplebucket-1250000000";
// A unique user-level resource identifier for developers accessing COS services, used to identify resources. It can be obtained on the https://console.tencentcloud.com/cam/capi page.
char appid[] = "1250000000";
// Project Identity ID/Key credentials for developers, which can be obtained on the https://console.tencentcloud.com/cam/capi page.
char secret_id[] = "xxxxxxxx";
char secret_key[] = "xxxxxxxxxxxx";
//endpoint is the domain information for accessing COS (without the bucket prefix, [bucket]-[appid] will be automatically prefixed when COS is accessed). For details, see the documentation at https://www.tencentcloud.com/document/product/436/6224.
char endpoint[] = "cos.ap-xxx.myqcloud.com";
// Whether to use a custom domain. If it is set to COS_TRUE, you need to modify the endpoint value to the custom domain when accessing COS.
int is_cname = COS_FALSE;
// Object name
char object_name[] = "test.txt";
// Local file path
char file_path[] = "test.txt";

void init_test_config(cos_config_t* config, int is_cname) {
cos_str_set(&config->endpoint, endpoint);
cos_str_set(&config->access_key_id, secret_id);
cos_str_set(&config->access_key_secret, secret_key);
cos_str_set(&config->appid, appid);
// cos_str_set(&config->sts_token, token); // token used when the temporary key is used
config->is_cname = is_cname; // whether to use a custom domain
}

void init_test_request_options(cos_request_options_t* options, int is_cname) {
options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);
}

void log_status(cos_status_t* s) {
cos_warn_log("status->code: %d", s->code);
if (s->error_code)
cos_warn_log("status->error_code: %s", s->error_code);
if (s->error_msg)
cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id)
cos_warn_log("status->req_id: %s", s->req_id);
}

void put_object_from_file_demo() {
cos_pool_t* p = NULL;
cos_status_t* s = NULL;
cos_request_options_t* options = NULL;
cos_string_t bucket;
cos_string_t object;
cos_string_t file;
cos_table_t* resp_headers = NULL;
cos_table_t* headers = NULL;

// Create a memory pool
cos_pool_create(&p, NULL);

// Initialize request options.
options = cos_request_options_create(p);
init_test_request_options(options, is_cname);
cos_str_set(&bucket, bucket_name);

// The speed limit value ranges from 819200 - 838860800 (100KB/s - 100MB/s). Values outside this range will return a 400 error.
// headers = cos_table_make(p, 1);
// cos_table_add_int(headers, "x-cos-traffic-limit", 819200);

// Upload object.
cos_str_set(&file, file_path);
cos_str_set(&object, object_name);
s = cos_put_object_from_file(options, &bucket, &object, &file, headers, &resp_headers);
if (cos_status_is_ok(s)) {
printf("put object succeeded\\n");
} else {
printf("put object failed\\n");
}
log_status(s);

// Destroy the memory pool.
cos_pool_destroy(p);
}

int main() {
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
exit(1);
}
// set log level, default COS_LOG_WARN
// cos_log_set_level(COS_LOG_WARN);
put_object_from_file_demo();

// cos_http_io_deinitialize last
cos_http_io_deinitialize();
return 0;
}
For the complete sample code, see: get_object_demo.c
// get_object_demo.c
#include <stdint.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include "cos_api.h"
#include "cos_http_io.h"
#include "cos_log.h"

/**
* This sample demonstrates how to use the COS SDK for C to perform object downloads (simple downloading).
*/

// Name of the COS bucket, in the format of [bucket]-[appid], such as examplebucket-1250000000. You can view it at https://console.tencentcloud.com/cos5/bucket
char bucket_name[] = "examplebucket-1250000000";
// A unique user-level resource identifier for developers accessing COS services, used to identify resources. It can be obtained on the https://console.tencentcloud.com/cam/capi page.
char appid[] = "1250000000";
// Project Identity ID/Key credentials for developers, which can be obtained on the https://console.tencentcloud.com/cam/capi page.
char secret_id[] = "xxxxxxxx";
char secret_key[] = "xxxxxxxxxxxx";
//endpoint is the domain information for accessing COS (without the bucket prefix, [bucket]-[appid] will be automatically prefixed when COS is accessed). For details, see the documentation at https://www.tencentcloud.com/document/product/436/6224.
char endpoint[] = "cos.ap-xxx.myqcloud.com";
// Whether to use a custom domain. If it is set to COS_TRUE, you need to modify the endpoint value to the custom domain when accessing COS.
int is_cname = COS_FALSE;
// Object name
char object_name[] = "test.txt";
// Local file path
char file_path[] = "test.txt";

void init_test_config(cos_config_t* config, int is_cname) {
cos_str_set(&config->endpoint, endpoint);
cos_str_set(&config->access_key_id, secret_id);
cos_str_set(&config->access_key_secret, secret_key);
cos_str_set(&config->appid, appid);
// cos_str_set(&config->sts_token, token); // token used when a temporary key is used
config->is_cname = is_cname; // whether to use a custom domain
}

void init_test_request_options(cos_request_options_t* options, int is_cname) {
options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);
}

void log_status(cos_status_t* s) {
cos_warn_log("status->code: %d", s->code);
if (s->error_code)
cos_warn_log("status->error_code: %s", s->error_code);
if (s->error_msg)
cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id)
cos_warn_log("status->req_id: %s", s->req_id);
}

void get_object_to_file_demo() {
cos_pool_t *p = NULL;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;
cos_table_t *resp_headers;
cos_string_t file;
cos_table_t *headers = NULL;
cos_table_t *params = NULL;

cos_pool_create(&p, NULL);
options = cos_request_options_create(p);
init_test_request_options(options, is_cname);
cos_str_set(&bucket, bucket_name);
cos_str_set(&file, file_path);
cos_str_set(&object, object_name);

// The speed limit value ranges from 819200 - 838860800 (100KB/s - 100MB/s). Values outside this range will return a 400 error.
// headers = cos_table_make(p, 1);
// cos_table_add_int(headers, "x-cos-traffic-limit", 819200);
s = cos_get_object_to_file(options, &bucket, &object, headers, params, &file, &resp_headers);
log_status(s);

{
int i = 0;
apr_array_header_t * pp = (apr_array_header_t *) apr_table_elts(resp_headers);
for ( ; i < pp->nelts; i++) {
apr_table_entry_t *ele = (apr_table_entry_t *)pp->elts+i;
printf("%s: %s\\n", ele->key, ele->val);
}
}

cos_pool_destroy(p);
}


int main() {
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
exit(1);
}
// set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);
get_object_to_file_demo();
// cos_http_io_deinitialize last
cos_http_io_deinitialize();
return 0;
}
Note:
Once an object is deleted, its corresponding data will no longer be accessible.
For the complete sample code, see: delete_object_demo.c
// delete_object_demo.c
#include <stdint.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include "cos_api.h"
#include "cos_http_io.h"
#include "cos_log.h"

/**
* This sample demonstrates how to use the COS SDK for C to perform object deletion (single object deletion).
*/

// Name of the COS bucket, in the format of [bucket]-[appid], such as examplebucket-1250000000. You can view it at https://console.tencentcloud.com/cos5/bucket
char bucket_name[] = "examplebucket-1250000000";
// A unique user-level resource identifier for developers accessing COS services, used to identify resources. It can be obtained on the https://console.tencentcloud.com/cam/capi page.
char appid[] = "1250000000";
// Project Identity ID/Key credentials for developers, which can be obtained on the https://console.tencentcloud.com/cam/capi page.
char secret_id[] = "xxxxxxxx";
char secret_key[] = "xxxxxxxxxxxx";
//endpoint is the domain information for accessing COS (without the bucket prefix, [bucket]-[appid] will be automatically prefixed when COS is accessed). For details, see the documentation at https://www.tencentcloud.com/document/product/436/6224.
char endpoint[] = "cos.ap-xxx.myqcloud.com";
// Whether to use a custom domain. If set to COS_TRUE, you need to modify the endpoint value to the custom domain when accessing COS.
int is_cname = COS_FALSE;
// Object name
char object_name[] = "test.txt";

void init_test_config(cos_config_t* config, int is_cname) {
cos_str_set(&config->endpoint, endpoint);
cos_str_set(&config->access_key_id, secret_id);
cos_str_set(&config->access_key_secret, secret_key);
cos_str_set(&config->appid, appid);
// cos_str_set(&config->sts_token, token); // token used when a temporary key is used
config->is_cname = is_cname; // whether to use a custom domain
}

void init_test_request_options(cos_request_options_t* options, int is_cname) {
options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);
}

void log_status(cos_status_t* s) {
cos_warn_log("status->code: %d", s->code);
if (s->error_code)
cos_warn_log("status->error_code: %s", s->error_code);
if (s->error_msg)
cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id)
cos_warn_log("status->req_id: %s", s->req_id);
}

void delete_object_demo() {
cos_pool_t *p = NULL;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;
cos_string_t src_object;
cos_string_t src_endpoint;
cos_table_t *resp_headers = NULL;

//Creating a memory pool.
cos_pool_create(&p, NULL);

//Initializing the request options.
options = cos_request_options_create(p);
init_test_request_options(options, is_cname);
cos_str_set(&bucket, bucket_name);

//Setting the object.
cos_str_set(&object, object_name);

s = cos_delete_object(options, &bucket, &object, &resp_headers);
log_status(s);
if (cos_status_is_ok(s)) {
printf("delete object succeeded\\n");
} else {
printf("delete object failed\\n");
}

//Destroying the memory pool.
cos_pool_destroy(p);
}

int main() {
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
exit(1);
}
// set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);
delete_object_demo();
// cos_http_io_deinitialize last
cos_http_io_deinitialize();
return 0;
}

Compile and Run the Demo Example

Still taking Linux as an example, ensure that the PKG_CONFIG_PATH and LD_LIBRARY_PATH environment variables are set during installation.

Compilation

Execute:
pkg-config --cflags --libs apr-1 apr-util-1 mxml libcurl
Compilation options available:
-I/usr/local/apr/include/apr-1 -DLINUX -D_GNU_SOURCE -g -O2 -pthread -I/usr/local/include -D_THREAD_SAFE -D_REENTRANT -L/usr/local/apr/lib -laprutil-1 -lexpat -lapr-1 -lrt -lcrypt -ldl -L/usr/local/lib -lmxml -lpthread -lcurl
It is also necessary to add the compilation options for cos-c-sdk-I/usr/local/include/cos_c_sdk -lcos_c_sdk, and the final compilation options are as follows:
-I/usr/local/include/cos_c_sdk -I/usr/local/apr/include/apr-1 -I/usr/local/include -DLINUX -D_GNU_SOURCE -g -O2 -pthread -D_THREAD_SAFE -D_REENTRANT -L/usr/local/lib -lcos_c_sdk -L/usr/local/apr/lib -laprutil-1 -lexpat -lapr-1 -lrt -lcrypt -ldl -lmxml -lpthread -lcurl
Note:
In the latest commit, cos-c-sdk supports pkg-config. You can directly run the commandpkg-config --cflags --libs cos_c_sdk apr-1 apr-util-1 mxml libcurl to generate compilation options with cos-c-sdk information.
Taking get_bucket_list_demo.c as an example, after configuring parameters such as appid, secret_id, secret_key, and endpoint in the code, use the following command to compile:
gcc get_bucket_list_demo.c -o get_bucket_list_demo -I/usr/local/include/cos_c_sdk -I/usr/local/apr/include/apr-1 -I/usr/local/include -DLINUX -D_GNU_SOURCE -g -O2 -pthread -D_THREAD_SAFE -D_REENTRANT -L/usr/local/lib -lcos_c_sdk -L/usr/local/apr/lib -laprutil-1 -lexpat -lapr-1 -lrt -lcrypt -ldl -lmxml -lpthread -lcurl

Running

Run the newly compiled binary:
./get_bucket_list_demo
If the operation is successful and there are buckets under the current appid, then get_bucket_list_demo will list all buckets under the current account.

FAQs

You may encounter some common issues during usage. For solutions, refer to C SDK FAQ.


Ajuda e Suporte

Esta página foi útil?

comentários