Check bucket existence (OSS C++ SDK V2)

更新时间:
复制 MD 格式

Use the OSS C++ SDK V2 to check whether a bucket exists before you perform operations on it.

Usage notes

  • Before you run the sample code, replace <region> in the code with a valid region, such as cn-hangzhou.

  • The sample code in this topic obtains access credentials from environment variables.

  • To get information about a bucket, you must have the oss:GetBucketInfo permission.

Sample code

The following code uses the isBucketExist method to check whether a bucket exists:

#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region>";
    conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();

    oss::OSSClient client(conf);

    auto outcome = client.isBucketExist("examplebucket");

    if (!outcome.has_value()) {
        auto& e = outcome.error();
        std::cerr << "Failed to check if the bucket exists"
                  << ", code: " << e.getCode()
                  << ", message: " << e.getMessage()
                  << ", requestId: " << e.getRequestId() << std::endl;
        return 1;
    }

    std::cout << "Bucket \"examplebucket\" "
              << (outcome.value() ? "exists" : "does not exist") << std::endl;
    return 0;
}
        
Note

The isBucketExist method returns true if the bucket exists and false otherwise. If an error occurs (outcome.has_value() is false), you cannot determine whether the bucket exists. In this case, check the error message for details.

References