Tous les produits
Search
Centre de documentation

Object Storage Service:List objects (C++ SDK)

Dernière mise à jour :Aug 18, 2026

Cette rubrique explique comment répertorier tous les objets d'un bucket spécifié, limiter le nombre d'objets répertoriés et obtenir la taille totale des objets contenus dans un dossier spécifique.

Informations générales

Les objets OSS sont triés par ordre alphabétique. Utilisez OssClient.ListObjects pour répertorier les objets d'un bucket. La méthode ListObjects accepte trois formats de paramètres :

  • ListObjectOutcome ListObjects(const std::string& bucket) const : répertorie les objets d'un bucket. Une seule requête renvoie au maximum 1 000 objets.

  • ListObjectOutcome ListObjects(const std::string& bucket, const std::string& prefix) const : répertorie les objets d'un bucket qui partagent un préfixe donné. Une seule requête renvoie au maximum 1 000 objets.

  • ListObjectOutcome ListObjects(const ListObjectsRequest& request) const : offre plusieurs options de filtrage pour des requêtes flexibles.

Le tableau suivant décrit les principaux paramètres.

Paramètre

Description

delimiter

Caractère utilisé pour regrouper les noms d'objets. Tous les objets dont le nom contient le préfixe spécifié et qui apparaissent entre ce préfixe et la première occurrence du délimiteur sont regroupés en un ensemble (commonPrefixes).

prefix

Indique que les objets renvoyés doivent comporter le préfixe spécifié.

maxKeys

Nombre maximal d'objets à renvoyer dans cette requête. La valeur par défaut est 100. La valeur maximale est 1 000.

marker

Répertorie les objets qui apparaissent après le marqueur spécifié.

Notes

  • Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Si vous souhaitez 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 montre 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 Security Token Service (STS), consultez Créer une instance OssClient.

  • Pour répertorier les objets, vous devez disposer de l'autorisation oss:ListObjects. Pour plus d'informations, consultez Accorder une politique personnalisée.

Répertorier les objets

L'exemple de code suivant montre comment répertorier les objets d'un bucket spécifié. Par défaut, 100 objets sont renvoyés.

#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. 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 configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* List objects. */
    ListObjectsRequest request(BucketName);
    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;
        return -1;  
    }
    else {
        for (const auto& object : outcome.result().ObjectSummarys()) {
            std::cout << "object"<<
            ",name:" << object.Key() <<
            ",size:" << object.Size() <<
            ",last modified time:" << object.LastModified() << std:: endl;
         }      
    }

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

Répertorier un nombre défini d'objets

L'exemple de code suivant montre comment répertorier un nombre spécifique d'objets.

#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. 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 configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* List objects. */
    ListObjectsRequest request(BucketName);
    /* Set the maximum number of objects to list to 200. */
    request.setMaxKeys(200);
    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;
        return -1;  
    }
    else {
        for (const auto& object : outcome.result().ObjectSummarys()) {
            std::cout << "object"<<
            ",name:" << object.Key() <<
            ",size:" << object.Size() <<
            ",last modified time:" << object.LastModified() << std ::endl; 
        }      
    }

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

Répertorier les objets et sous-dossiers d'un dossier spécifique

L'exemple de code suivant montre comment répertorier les objets et les sous-dossiers d'un dossier spécifié :

#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. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the prefix of the objects to list. */
    std::string keyPrefix = "yourkeyPrefix";

     /* 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 configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    std::string nextMarker = "";
    bool isTruncated = false;  
    do {
        /* List objects. */
        ListObjectsRequest request(BucketName);
         /* Set the forward slash (/) as the folder separator. */
        request.setDelimiter("/");
        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()) {
            std::cout << "object"<<
            ",name:" << object.Key() <<
            ",size:" << object.Size() <<
            ",last modified time:" << object.LastModified() << std::endl;
        }
        for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
            std::cout << "commonPrefix" << ",name:" << commonPrefix << std::endl;
        }
        nextMarker = outcome.result().NextMarker();
        isTruncated = outcome.result().IsTruncated();
    } while (isTruncated);

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

Obtenir la taille des objets d'un dossier spécifique

L'exemple de code suivant montre comment obtenir la taille totale des objets d'un dossier spécifié :

#include <iostream>
#include <alibabacloud/oss/OssClient.h>

using namespace AlibabaCloud::OSS;

static int64_t calculateFolderLength(const OssClient &client, const std::string &bucketName, const std::string &folder)
{
    std::string nextMarker = "";
    bool isTruncated = false; 
    int64_t size = 0;
    do {
        /* List objects. */
        ListObjectsRequest request(bucketName);
        request.setPrefix(folder);
        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()) {
            size += object.Size();
        }
        nextMarker = outcome.result().NextMarker();
        isTruncated = outcome.result().IsTruncated();
    } while (isTruncated);
    return size;
}

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. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the prefix of the objects to list. */
    std::string keyPrefix = "yourkeyPrefix";
	
    /* 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 configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
    std::string nextMarker = "";
    bool isTruncated = false; 
    do {
        /* List objects. */
        ListObjectsRequest request(BucketName);
        /* Set the forward slash (/) as the folder separator. */
        request.setDelimiter("/");
        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()) {
            std::cout << "object" <<
            ",name:" << object.Key() <<
            ",size:" << object.Size() << std::endl;
        }
        for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
            int64_t foldersize = calculateFolderLength(client, BucketName, commonPrefix);
            std::cout << "folder" <<
            ",name:" << commonPrefix <<
            ",size:" << foldersize << std::endl;
        }
        nextMarker = outcome.result().NextMarker();
        isTruncated = outcome.result().IsTruncated(); 
    } while (isTruncated);
    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Répertorier les objets avec un préfixe spécifique

L'exemple de code suivant montre comment répertorier les objets qui possèdent un préfixe donné.

#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. Example: examplebucket. */
     std::string BucketName = "examplebucket";
     /* Specify the prefix of the objects to list. */
     std::string keyPrefix = "yourkeyPrefix";

      /* 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 configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
      std::string nextMarker = "";
      bool isTruncated = false; 
      do {
              /* List objects. */
              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()) {
                  std::cout << "object"<<
              ",name:" << object.Key() <<
              ",size:" << object.Size() <<
              ",last modified time:" << object.LastModified() << std::endl;
            }      
              nextMarker = outcome.result().NextMarker();
              isTruncated = outcome.result().IsTruncated();
      } while (isTruncated);

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

Répertorier les objets situés après un marqueur spécifique

Le paramètre marker indique un nom d'objet. L'exemple de code suivant montre comment répertorier les objets qui apparaissent après un marqueur donné.

#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. Example: examplebucket. */
      std::string BucketName = "examplebucket";
      /* Set the marker. */
      std::string YourMarker = "yourMarker";

      /* 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 configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
      
    ListObjectOutcome outcome;
      do {
              /* List objects. */
              ListObjectsRequest request(BucketName);
              /* List objects that appear after the specified marker. */
              request.setMarker(YourMarker);
              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;  
              }
            YourMarker = outcome.result().NextMarker();
            for (const auto& object : outcome.result().ObjectSummarys()) {
                       std::cout << "object"<<
                  ",name:" << object.Key() <<
                ",size:" << object.Size() <<
                ",last modified time:" << object.LastModified() << std::endl;
            }      
      } while (outcome.result().IsTruncated());

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

Spécifier l'encodage des noms d'objets

Si un nom d'objet contient des caractères spéciaux, vous devez encoder ce nom en URL pour la transmission. OSS prend uniquement en charge l'encodage URL.

  • Guillemets simples (')

  • Guillemets doubles ("")

  • Esperluettes (&)

  • Chevrons (< >)

  • Caractères chinois

L'exemple de code suivant montre comment spécifier l'encodage des noms d'objets :

#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. 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 configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    std::string nextMarker = "";
    bool isTruncated = false; 
    do {
        /* List objects. */
        ListObjectsRequest request(BucketName) ;
        /* Specify the encoding of object names. */
        request.setEncodingType("url");
        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()) {
            std::cout << "object"<<
            ",name:" << object.Key() <<
            ",size:" << object.Size() <<
            ",last modified time:" << object.LastModified() << std::endl;
        }      
        nextMarker = outcome.result().NextMarker();
        isTruncated = outcome.result().IsTruncated();
    } while (isTruncated);

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

Fonctionnalité de dossier

OSS ne repose pas sur le concept de dossiers. Tous les éléments sont stockés sous forme d'objets. Créer un dossier revient à créer un objet de zéro octet se terminant par une barre oblique (/). Cet objet peut être téléchargé et téléversé. La console OSS affiche les objets se terminant par une barre oblique (/) comme des dossiers.

Spécifiez les paramètres delimiter et prefix pour répertorier les objets par répertoire.

  • Si vous définissez prefix sur un nom de répertoire dans la requête, les objets et sous-répertoires dont les noms contiennent ce préfixe sont répertoriés.

  • Si vous spécifiez un préfixe et définissez delimiter sur une barre oblique (/) dans la requête, les objets et sous-répertoires dont les noms commencent par le préfixe indiqué dans le répertoire sont répertoriés. Chaque sous-répertoire apparaît comme un élément de résultat unique dans CommonPrefixes. Les objets et répertoires contenus dans ces sous-répertoires ne sont pas répertoriés.

Par exemple, un bucket contient les objets suivants : oss.jpg, fun/test.jpg, fun/movie/001.avi, et fun/movie/007.avi. La barre oblique (/) est spécifiée comme séparateur de répertoire. Les exemples suivants décrivent comment répertorier les objets dans des répertoires simulés.

  • Répertorier tous les objets d'un bucket

    L'exemple de code suivant montre comment répertorier tous les objets d'un bucket spécifié.

    #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. 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 configured. */
        auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
        OssClient client(Endpoint, credentialsProvider, conf);
        client.SetRegion(Region);
    
        std::string nextMarker = "";
        bool isTruncated = false; 
        do {
            /* List objects. */
            ListObjectsRequest request(BucketName);
            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;
                ShutdownSdk();
                return -1;  
            }
            else {
                for (const auto& object : outcome.result().ObjectSummarys()) {
                    std::cout << "object"<<
                    ",name:" << object.Key() <<
                    ",size:" << object.Size() <<
                    ",last modified time:" << object.LastModified() << std::endl;
                }      
            }
            nextMarker = outcome.result().NextMarker();
            isTruncated = outcome.result().IsTruncated();
        } while (isTruncated);
    
        /* Release network resources. */
        ShutdownSdk();
        return 0;
    }

    Le résultat suivant est renvoyé :

    Objects:
    fun/movie/001.avi
    fun/movie/007.avi
    fun/test.jpg
    oss.jpg
    
    CommonPrefixes:
  • Répertorier tous les objets d'un dossier spécifique

    L'exemple de code suivant montre comment répertorier tous les objets d'un dossier spécifié.

    #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. 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 configured. */
        auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
        OssClient client(Endpoint, credentialsProvider, conf);
        client.SetRegion(Region);
    
        std::string nextMarker = "";
        bool isTruncated = false; 
        do {
                /* List objects. */
                ListObjectsRequest request(BucketName);
                request.setPrefix("fun/");
                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()) {
                    std::cout << "object"<<
                    ",name:" << object.Key() <<
                    ",size:" << object.Size() <<
                    ",last modified time:" << object.LastModified() << std::endl;
                }
                for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
                    std::cout << "commonPrefix" << ",name:" << commonPrefix << std::endl;
                }
                nextMarker = outcome.result().NextMarker();
                isTruncated = outcome.result().IsTruncated();
        } while (isTruncated);
    
        /* Release network resources. */
        ShutdownSdk();
        return 0;
    }

    Le résultat suivant est renvoyé :

    Objects:
    fun/movie/001.avi
    fun/movie/007.avi
    fun/test.jpg
    
    CommonPrefixes:
  • Répertorier les objets et sous-dossiers d'un dossier

    L'exemple de code suivant montre comment répertorier les objets et les sous-dossiers d'un dossier spécifié.

    #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. 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 configured. */
        auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
        OssClient client(Endpoint, credentialsProvider, conf);
        client.SetRegion(Region);
    
        std::string nextMarker = "";
        bool isTruncated = false;
        do {
                /* List objects. */
                ListObjectsRequest request(BucketName);
                /* Set the forward slash (/) as the folder separator. */
                request.setDelimiter("/");
                request.setPrefix("fun/");
                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()) {
                    std::cout << "object"<<
                    ",name:" << object.Key() <<
                    ",size:" << object.Size() <<
                    ",last modified time:" << object.LastModified() << std::endl;
                }
                for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
                    std::cout << "commonPrefix" << ",name:" << commonPrefix << std::endl;
                }
                nextMarker = outcome.result().NextMarker();
                isTruncated = outcome.result().IsTruncated();
        } while (isTruncated);
    
        /* Release network resources. */
        ShutdownSdk();
        return 0;
    }

    Le résultat suivant est renvoyé :

    Objects:
    fun/test.jpg
    
    CommonPrefixes:
    fun/movie/
  • Obtenir la taille des objets d'un dossier spécifique

    L'exemple de code suivant montre comment obtenir la taille totale des objets d'un dossier spécifié :

    #include <alibabacloud/oss/OssClient.h>
    using namespace AlibabaCloud::OSS;
    
    static int64_t calculateFolderLength (const OssClient &client, const std::string &bucketName, const std::string &folder)
    {
        std::string nextMarker = "";
        bool isTruncated = false;
        int64_t size = 0;
        do {
                /* List objects. */
                ListObjectsRequest request(bucketName);
                request.setPrefix(folder);
                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()) {
                    size += object.Size();
                }
    
                nextMarker = outcome.result().NextMarker();
                isTruncated = outcome.result().IsTruncated();
            } while (isTruncated);
    
          return size;
    }
    
    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. 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 configured. */
        auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
        OssClient client(Endpoint, credentialsProvider, conf);
        client.SetRegion(Region);
    
        std::string nextMarker = "";
        bool isTruncated = false;
        do {
            /* List objects. */
            ListObjectsRequest request(BucketName);
            /* Set the forward slash (/) as the folder separator. */
            request.setDelimiter("/");
            request.setPrefix("fun/");
            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()) {
                std::cout << "object" <<
                ",name:" << object.Key() <<
                ",size:" << object.Size() << std::endl;
            }
    
            for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
                int64_t foldersize = calculateFolderLength(client, BucketName, commonPrefix);
                std::cout << "folder" <<
                ",name:" << commonPrefix <<
                ",size:" << foldersize << std::endl;
            }
            nextMarker = outcome.result().NextMarker();
            isTruncated = outcome.result().IsTruncated();
        } while (isTruncated);
    
        /* Release network resources. */
        ShutdownSdk();
        return 0;
    }

Références