Todos os produtos
Search
Central de documentação

Object Storage Service:Delete files (C++ SDK)

Última atualização: Jul 03, 2026

Exclua um único objeto, vários objetos por nome, objetos correspondentes a um prefixo ou um diretório inteiro.

Aviso

Não é possível recuperar objetos excluídos. Proceda com cautela.

Observações

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Criar uma instância OssClient.

  • A exclusão de um objeto exige a permissão oss:DeleteObject. Para obter mais informações, consulte Conceder uma política personalizada.

Excluir um único arquivo

O código a seguir exclui o objeto exampleobject.txt do bucket examplebucket:

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. For example, exampleobject.txt. The full path cannot contain the bucket name. */
    /* To delete a folder, set ObjectName to the folder name. If the folder is not empty, you must delete all objects in the folder before you can delete the folder. */
    std::string ObjectName = "exampleobject.txt";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
   
    DeleteObjectRequest request(BucketName, ObjectName);

    /* Delete the file. */
    auto outcome = client.DeleteObject(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "DeleteObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Excluir vários arquivos em lote

Você pode excluir até 1.000 objetos por vez por nome, prefixo ou diretório.

Ao excluir vários arquivos, os resultados retornam em um dos dois modos seguintes. O modo padrão é Verbose.

  • Modo Verbose: retorna uma lista de todos os arquivos excluídos.

  • Modo Basic: retorna apenas a lista de arquivos cuja exclusão falhou.

Também é possível configurar regras de ciclo de vida para excluir objetos automaticamente. Para obter mais informações, consulte Regras de ciclo de vida baseadas na última modificação.

Excluir vários objetos com nomes especificados

O código a seguir exclui vários objetos por nome:

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    DeleteObjectsRequest request(BucketName);
    /* Add the full paths of the objects to delete. */
    request.addKey("yourObjectName1");
    request.addKey("yourObjectName2");
  
    /* Delete the files. */
    auto outcome = client.DeleteObjects(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "DeleteObjects fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Excluir vários objetos com o prefixo de nome especificado ou no diretório especificado

O código a seguir exclui objetos por prefixo ou remove um diretório inteiro:

Aviso

Se o valor do parâmetro keyPrefix no código de exemplo a seguir for uma string vazia ou nulo, todos os arquivos do bucket serão excluídos. Use esse recurso com cautela.

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* If you want to delete all files that have the prefix src, set the prefix to src. After you set the prefix to src, all non-folder files that have the prefix src, the src folder, and all files in the src folder are deleted. */
    std::string keyPrefix = "src";
    /* If you want to delete only the src folder and all files in it, set the prefix to src/. */
    /* std::string keyPrefix = "src/"; */

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    std::string nextMarker = "";
    bool isTruncated = false;
    do {
            /* List the files. */
            ListObjectsRequest request(BucketName);           
            request.setPrefix(keyPrefix);
            request.setMarker(nextMarker);
            auto outcome = client.ListObjects(request);

            if (!outcome.isSuccess()) {
                /* Handle exceptions. */
                std::cout << "ListObjects fail" <<
                ",code:" << outcome.error().Code() <<
                ",message:" << outcome.error().Message() <<
                ",requestId:" << outcome.error().RequestId() << std::endl;
                break;
            }
            for (const auto& object : outcome.result().ObjectSummarys()) {
                DeleteObjectRequest request(BucketName, object.Key());
                /* Delete the file. */
                auto delResult = client.DeleteObject(request);
            }
            nextMarker = outcome.result().NextMarker();
            isTruncated = outcome.result().IsTruncated();
    } while (isTruncated);

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Referências