Check if bucket exists
Updated at:2025-11-03
Check if bucket exists
If users need to determine whether a bucket exists, the following code can achieve this:
C++
1//0 indicates a successful check and the bucket exists
2 //-1 indicates non-existence
3 // other indicates other errors, with specific error-message provided
4int checkBucketExist (Client& client, const std::string& bucketName) {
5 bool exist = false;
6 // Retrieve bucket existence information
7 HeadBucketRequest request(bucketName);
8 HeadBucketResponse response;
9 int ret = client.head_bucket(request, &response);
10 if (response.is_fail() && response.status_code() != 404){
11 printf("error-message:%s\n", response.error().message().c_str());
12 return ret;
13 } else if (response.status_code() == 404){
14 return -1;
15 }
16 //200 ok
17 return 0;
18}
Note: If the bucket is not null (that is, there are objects in the bucket), the bucket cannot be deleted. The bucket must be emptied before it can be deleted successfully.
