Check if a bucket exists (C++ SDK)

Updated at:

A bucket is a container used to store objects in Object Storage Service (OSS). This topic describes how to determine whether a bucket exists.

Notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • This topic demonstrates creating an OSSClient instance with an OSS endpoint. For alternative configurations, such as using a custom domain or authenticating with credentials from Security Token Service (STS), see Create an OssClient instance.

  • To determine whether a bucket exists, you must have the oss:GetBucketAcl permission. For more information, see Grant a custom policy.

Sample code

The following code shows how to check whether the bucket named examplebucket exists.

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    
    /* Specify the bucket name, such as examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Check if the bucket exists. */
    auto outcome = client.DoesBucketExist(BucketName);

    if (outcome) {    
        std::cout << " The Bucket exists" << std::endl;
    }
    else {
        std::cout << "The Bucket does not exist" << std::endl;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}