C program to access a local file using curl

Posted by Joys of Programming on in C/C++

Curl is used to access the internet, both from the command line and using a C Program. But do you know that you can also use it to access the local files.

The FILE protocol is used to access the local files

To access the local files, you must enter the path in your browser with file:// superseding the path. Take for example, if you want to access /home/user/Desktop, enter file:///home/user/Desktop in the address bar. The file listing will be displayed.

Similarly you can make use of the FILE protocol to access the local files using curl. If you are working offline, and you want to experiment with curl, using curl and setting the URL path with file:// will help you experiment a lot

The following program depicts this


#include <curl/curl.h>
#include <stdio.h>

size_t write_data( void *ptr, size_t size, size_t nmeb, void *stream)
{
  return fwrite(ptr,size,nmeb,stream);
}

int main()
{
  FILE * file = fopen("/home/user/data.txt","w+");
  if(!file){
    perror("File Open:");
  }
  CURL *handle = curl_easy_init();
  curl_easy_setopt(handle,CURLOPT_URL,"file:///usr/share/ubuntu-artwork/home/index.html"); /*Using the file protocol*/
  curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION, write_data);
  curl_easy_setopt(handle,CURLOPT_WRITEDATA, file);
  curl_easy_perform(handle);
  curl_easy_cleanup(handle);
}

As you can see, how the CURLOPT_URL was set with the local path. The content of the file is written to data.txt. You can also open stdout, to direct the output to the terminal

Tags: , , , , , ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.