Todos los productos
Search
Centro de documentos

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

Última actualización: Sep 24, 2026

Este tema describe cómo listar todos los objetos de un bucket específico, listar una cantidad determinada de objetos y obtener el tamaño total de los objetos en una carpeta específica.

Contexto

Los objetos de OSS se ordenan alfabéticamente. Para listar los objetos de un bucket, utilice OssClient.ListObjects. Este método admite a continuación tres formatos de parámetro:

  • ListObjectOutcome ListObjects(const std::string& bucket) const: lista los objetos de un bucket. Una sola solicitud devuelve un máximo de 1,000 objetos.

  • ListObjectOutcome ListObjects(const std::string& bucket, const std::string& prefix) const: lista los objetos de un bucket que tienen un prefijo específico. Una sola solicitud devuelve un máximo de 1,000 objetos.

  • ListObjectOutcome ListObjects(const ListObjectsRequest& request) const: ofrece varias funciones de filtrado para consultas flexibles.

A continuación se describen los parámetros principales.

Parámetro

Descripción

delimiter

Carácter que se usa para agrupar nombres de objetos. Todos los objetos cuyo nombre contiene el prefijo especificado y que aparecen entre dicho prefijo y la primera aparición del delimitador se agrupan en un conjunto (commonPrefixes).

prefix

Indica que los objetos devueltos deben tener el prefijo especificado.

maxKeys

Número máximo de objetos que se devuelven en esta solicitud. El valor predeterminado es 100. El valor máximo es 1,000.

marker

Lista los objetos que aparecen después del marcador especificado.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, use un endpoint interno. Para más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • En este tema se muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Create an OssClient instance.

  • Para listar objetos, debe contar con el permiso oss:ListObjects. Para más información, consulte Grant a custom policy.

Listar objetos

El siguiente código muestra cómo listar los objetos de un bucket específico. De forma predeterminada, se devuelven 100 objetos.

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

Listar una cantidad específica de objetos

El siguiente código muestra cómo listar una cantidad determinada de objetos.

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

Listar objetos y subcarpetas en una carpeta específica

El siguiente código muestra cómo listar los objetos y las subcarpetas de una carpeta específica:

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

Listar el tamaño de los objetos en una carpeta específica

El siguiente código muestra cómo obtener el tamaño total de los objetos almacenados en una carpeta específica:

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

Listar objetos con un prefijo específico

El siguiente código muestra cómo listar los objetos que tienen un prefijo determinado.

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

Listar objetos después de un marcador específico

El parámetro marker indica el nombre de un objeto. El siguiente código muestra cómo listar los objetos que aparecen después de un marcador determinado.

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

Especificar la codificación de los nombres de objeto

Si el nombre de un objeto contiene caracteres especiales, debe codificarlo con URL para transmitirlo. OSS solo admite la codificación URL.

  • Comillas simples (')

  • Comillas dobles ("")

  • Signos et (&)

  • Corchetes angulares (< >)

  • Caracteres chinos

El siguiente código muestra cómo especificar la codificación de los nombres de objeto:

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

Función de carpetas

OSS no maneja el concepto de carpetas; todos los elementos se almacenan como objetos. Crear una carpeta equivale a crear un objeto de cero bytes cuyo nombre termina con una barra diagonal (/). Este objeto se puede subir y descargar. La consola de OSS muestra los objetos que terminan con una barra diagonal (/) como carpetas.

Para listar objetos por directorio, especifique los parámetros delimiter y prefix.

  • Si establece prefix con el nombre de un directorio en la solicitud, se listan los objetos y subdirectorios cuyos nombres contienen ese prefijo.

  • Si especifica un prefijo y establece delimiter con una barra diagonal (/) en la solicitud, se listan los objetos y subdirectorios del directorio cuyos nombres comienzan con dicho prefijo. Cada subdirectorio aparece como un único elemento de resultado en CommonPrefixes. Los objetos y directorios dentro de esos subdirectorios no se listan.

Por ejemplo, suponga que un bucket contiene los siguientes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi y fun/movie/007.avi. Se define la barra diagonal (/) como delimitador de directorios. A continuación se describe cómo listar objetos en directorios simulados.

  • Listar todos los objetos de un bucket

    El siguiente código muestra cómo listar todos los objetos de un bucket específico.

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

    Se devuelve el siguiente resultado:

    Objects:
    fun/movie/001.avi
    fun/movie/007.avi
    fun/test.jpg
    oss.jpg
    
    CommonPrefixes:
  • Listar todos los objetos de una carpeta específica

    El siguiente código muestra cómo listar todos los objetos de una carpeta específica.

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

    Se devuelve el siguiente resultado:

    Objects:
    fun/movie/001.avi
    fun/movie/007.avi
    fun/test.jpg
    
    CommonPrefixes:
  • Listar objetos y subcarpetas de una carpeta

    El siguiente código muestra cómo listar los objetos y las subcarpetas de una carpeta específica.

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

    Se devuelve el siguiente resultado:

    Objects:
    fun/test.jpg
    
    CommonPrefixes:
    fun/movie/
  • Listar el tamaño de los objetos en una carpeta específica

    El siguiente código muestra cómo obtener el tamaño total de los objetos almacenados en una carpeta específica:

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

Referencias