Check if a bucket exists (C++ SDK)

Updated at:
Copy as MD

Use DoesBucketExist() to check whether a specified bucket exists and is accessible with your credentials.

Prerequisites

Before you begin, make sure you have:

  • The oss:GetBucketAcl permission on the target bucket. For setup instructions, see Attach a custom policy to a RAM user.

  • The OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables set with your AccessKey ID and AccessKey secret.

Usage notes

  • The examples in this topic use the public endpoint for the China (Hangzhou) region. To access OSS from another Alibaba Cloud service in the same region, use the internal endpoint instead. For a full list of endpoints, see Regions and endpoints.

  • To create an OSSClient instance using a custom domain name or Security Token Service (STS), see Create an OSSClient instance.

Check if a bucket exists

The following example checks whether the bucket examplebucket exists.

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

int main(void)
{
    /* Set the endpoint of the region where the bucket is located.
       Example: https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou). */
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

    /* Set the region ID where the bucket is located.
       Example: cn-hangzhou for China (Hangzhou). */
    std::string Region = "cn-hangzhou";

    /* Specify the bucket name. */
    std::string BucketName = "examplebucket";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;

    /* Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. */
    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;
}

Replace the sample values with your actual values:

VariableDescriptionExample
EndpointThe endpoint of the region where the bucket is locatedhttps://oss-cn-hangzhou.aliyuncs.com
RegionThe region ID where the bucket is locatedcn-hangzhou
BucketNameThe name of the bucket to checkexamplebucket