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 ascn-hangzhou. -
The sample code in this topic obtains access credentials from environment variables.
-
To get information about a bucket, you must have the
oss:GetBucketInfopermission.
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
-
For the complete sample code, see IsBucketExist.cpp.
该文章对您有帮助吗?