C program to access a local file using curl
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: Address bar, C file input/output, curl, curl programming, local files, Programming, Web browser
Comments:
On Facebook
Translate









Search
Custom SearchRecent Comments
- Ash on log4cpp::PatternLayout – Available log4cpp log formats
- Joys of Programming on Curl / libCurl Tutorials with Examples
- Malik89 on Curl / libCurl Tutorials with Examples
- Matt on How to install java library for jogl in Ubuntu/Linux?
- Gokulnath on How to install Readline/libreadline in Ubuntu?
On Twitter
Tutorials
Twitter
- And you thought Eclipse is Just for Java Development. You can also use Eclipse for C/C++ development http://t.co/swtOLbkr 3 months ago
- For the C fans here, let's see a simple question. Is there any difference between func() and func(void)? http://t.co/ASTsWVc9 3 months ago
- ISO C++11 released. http://t.co/DyJ0rSa1 3 months ago
- RT @newsycombinator: IE team sends a cupcake for FireFox 5 http://j.mp/lS7pGF 7 months ago
- RT @newsycombinator: Voice search enabled on Google homepage (Chrome) http://j.mp/m5KT8c 7 months ago
Categories