Note: This tutorial assumes that you have completed the previous tutorials: ROS Tutorials.

Retrieving Files

Description: Demonstrates how to retrieve a file from a URL using the resource_retriever package

Keywords: urdf, resource_retriever, url, curl

Tutorial Level: BEGINNER

Intro

The resource_retriever package lets you download files from any CURL-supported URL, as well as using a special package:// syntax. Here we'll show you how to use it.

Retrieving a File Into Memory

Here we'll show you how to retrieve a file from a URL into memory, which is currently the only supported method of retrieval.

The Code

   1 #include <resource_retriever/retriever.h>
   2 #include <ros/console.h>
   3 
   4 int main(int argc, char** argv)
   5 {
   6   resource_retriever::Retriever r;
   7   resource_retriever::MemoryResource resource;
   8 
   9   try
  10   {
  11      resource = r.get("package://resource_retriever/test/test.txt"); 
  12   }
  13   catch (resource_retriever::Exception& e)
  14   {
  15     ROS_ERROR("Failed to retrieve file: %s", e.what());
  16     return 1;
  17   }
  18 
  19   FILE* f = fopen("out.txt", "w");
  20   fwrite(resource.data.get(), resource.size, 1, f);
  21   fclose(f);
  22   
  23   ROS_INFO("Wrote data from package://resource_retriever/test/test.txt to out.txt");
  24 }

The Code Explained

   1 #include <resource_retriever/retriever.h>
   2 

This is the main include file for resource_retriever. It includes the two main classes, resource_retriver::Retreiver and resource_retriever::MemoryResource.

   6   resource_retriever::Retriever r;
   7   resource_retriever::MemoryResource resource;

Create the resource_retriever::Retriever object, which is the object used to retrieve files. Also create a resource_retriever::MemoryResource object, which is the object type returned from Retriever's get() method.

   9   try
  10   {
  11      resource = r.get("package://resource_retriever/test/test.txt"); 
  12   }
  13   catch (resource_retriever::Exception& e)
  14   {
  15     ROS_ERROR("Failed to retrieve file: %s", e.what());
  16     return 1;
  17   }

Attempt to download the file. Note the package:// syntax, which is ROS-specific. Generic urls like http://www.google.com/ would also work here.

If this fails for any reason, a resource_retriever::Exception will be thrown.

  19   FILE* f = fopen("out.txt", "w");
  20   fwrite(resource.data.get(), resource.size, 1, f);

Write out the downloaded file to disk. MemoryResource contains two members:

  • data -- a boost::shared_ptr<uint8_t>

  • size -- The size, in bytes, of the data

MemoryResources can be copied. Once all references to MemoryResource::data have left scope it will automatically be deleted.

Note that we don't do any error checking on the fopen or fwrite here, to simplify the code.

Wiki: resource_retriever/Tutorials/Retrieving Files (last edited 2009-10-05 23:17:32 by JoshFaust)