Check if an object exists (C++ SDK V2)

更新时间:
复制 MD 格式

You can use the OSS C++ SDK V2 to check whether an object exists in a bucket before you perform operations on the object.

Usage notes

  • Before you run the sample code, replace <region> with an actual region, such as cn-hangzhou.

  • The sample code uses environment variables to obtain access credentials.

  • To check whether an object exists, you must have the oss:GetObject permission.

Sample code

The following sample code calls the isObjectExist method to check whether an object 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.isObjectExist("examplebucket", "exampleobject.txt");

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

    std::cout << "The object \"exampleobject.txt\" "
              << (outcome.value() ? "exists" : "does not exist") << std::endl;
    return 0;
}
        
Note

isObjectExist returns true if the object exists and false if it does not. If an error occurs (outcome.has_value() returns false), you cannot determine whether the object exists. Check the error message for more information.

References