Tous les produits
Search
Centre de documentation

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

Dernière mise à jour :Aug 18, 2026

Supprimez un objet unique, plusieurs objets par nom, les objets correspondant à un préfixe ou un répertoire entier.

Avertissement

La suppression des objets est irréversible. Procédez avec prudence.

Remarques

  • Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.

  • Cette rubrique explique comment créer une instance OssClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Créer une instance OssClient.

  • Pour supprimer un objet, vous devez disposer de l'autorisation oss:DeleteObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Supprimer un seul fichier

Le code suivant supprime un objet nommé exampleobject.txt d'un bucket nommé 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;
}

Supprimer plusieurs fichiers par lot

Vous pouvez supprimer jusqu'à 1 000 objets simultanément par nom, par préfixe ou par répertoire.

Lors de la suppression de plusieurs fichiers, les résultats sont renvoyés selon l'un des deux modes suivants. Le mode par défaut est le mode Verbose.

  • Mode Verbose : renvoie la liste de tous les fichiers supprimés.

  • Mode Basic : renvoie uniquement la liste des fichiers dont la suppression a échoué.

Vous pouvez également configurer des règles de cycle de vie pour supprimer automatiquement les objets. Pour plus d'informations, consultez Règles de cycle de vie basées sur la dernière heure de modification.

Delete multiple objects with specified names

Le code suivant supprime plusieurs objets par nom :

#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;
}

Delete multiple objects with the specified object name prefix or in the specified directory

Le code suivant supprime des objets par préfixe ou un répertoire entier :

Avertissement

Si la valeur du paramètre keyPrefix dans l'exemple de code ci-dessous est une chaîne vide ou null, tous les fichiers du bucket sont supprimés. Utilisez cette fonctionnalité avec prudence.

#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;
}

Références

  • Pour l'exemple de code complet utilisé pour supprimer un ou plusieurs fichiers, consultez Exemple GitHub.

  • Opération API pour la suppression d'un seul fichier : DeleteObject.

  • Opération API pour la suppression de plusieurs fichiers : DeleteMultipleObjects.