Libcurl Initial implementation of TFP upload and download functions

Source: Internet
Author: User
Tags fread ftp file http post


The goal of the research report is to use Libcurl to implement FTP file upload and download functions

First, Libcurlde brief

Libcurl and easy-to-use libraries that use URLs for file transfers.

, Libcurl currently supports Dict, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, Ldap,ldaps, POP3, Pop3s, RTMP, RTSP, SCP, SFTP, SMTP , SMTPS, Telnet and TFTP protocol. Libcurl same support HTTPS certificate authorization, HTTP POST, http PUT, FTP upload, HTTP basic form upload. Agent. Cookies, and user authentication.

Libcurl is a lightweight library that can be compiled and executed onto a variety of platforms, including: Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64,linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac os X, Ultrix, Qnx,openvms, RISC OS, Novell NetWare, DOS etc.

Second, the Libcurl interface

The Libcurl is divided into simple and complex interfaces.

The simple interface is a synchronous, efficient, high-speed. Such excuses are used primarily for file transfer.

A large number of applications are used in this way. and the complex sister Puppet is an asynchronous, not doing much research here

Three, Libcurl simple interface Work flow

1. Use Curl_easy_init () in Libcurl to initialize a simple File transfer session and get to a handle

2. Set all option parameters by using curl_easy_setopt (). The most important thing in these parameters is the URL, and at the same time you will most likely need to set up some callback functions. These callback functions will be called when the condition is met.

3, when the above work is done. will be able to use Curl_easy_perform () notification libcurl for file transfer. The function returns a value when the entire transfer process is complete or fails.

4, after you run the 3rd step, you can use Curl_easy_getinfo () to get the transmitted information

5, finally, you can use Curl_easy_cleanup () to end this file session

For these five steps, write an example to test

Iv. Introduction to some function functions

1, CURL *curl_easy_init ();

The function must be called first and will return a curl* type of handle. And the function will be used in conjunction with Curl_easy_cleanup (). The function will return a NULL if the initialization error is increased.

2. void Curl_easy_cleanup (Curl *handle)

The function must be the last to be called, and his number should be the return value of Curl_easy_init;

3, Curlcode curl_easy_setopt (curl*handle, curloption option, parameter);

The function knows the number of parameters to be set from the name. By setting a different number of parameters, the function of Libcurl will be changed. This requires careful reading of the guidance document, once the Setup method is inappropriate, the resulting error will be fatal.

The use of specific parameters on this site describes the very specific narrative

Http://curl.haxx.se/libcurl/c/curl_easy_setopt.html

4, Curlcode curl_easy_perform (Curl * easy_handle);

As we have just mentioned, this function should be used after Init and setopt, and once this function is run, it will inform Libcurl to run all the methods we set before, it is worth noting that when a handle is added to a multi handle, The parameter handle will not be called by the function perform

V. Demonstration of examples

1, the following is a simple example:

#include <stdio.h> #include <curl/curl.h>int main (int argc,char** argv) {    Curl *pcurlhandle = NULL;    Curlcode errorCode = 0;    /*1. Initializes a pcurlhandle*/    pcurlhandle = Curl_easy_init ();     if (Pcurlhandle)    {        /*2. Set Pcurlhandle url*/        curl_easy_setopt (Pcurlhandle,curlopt_url, "http:// Blog.csdn.net/jxnu_xiaobing ");        /*3. As the above URLs have been redirected. So set to curlopt_followlocation*/        curl_easy_setopt (pcurlhandle,curlopt_followlocation, 1L);        /*4. Start running the above opt*/        ErrorCode = Curl_easy_perform (pcurlhandle);        if (errorCode! = Curle_ok)        {                printf ("Curl_easy_perform ()  failed \ n");}    }    else    {        printf ("Curl_easy_init ()  failed \ n");    }    /*5. Finally close pcurlhandle*/    curl_easy_cleanup (pcurlhandle);    return 0;}


2, the above example is relatively simple is a visit to the page sample. Continue to learn an example of FTP upload

#include <stdio.h> #include <string.h> #include <curl/curl.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #defineLOCAL_FILE "/tmp /xiaobing.txt "#defineREMOTE_URL" Ftp://172.30.26.247:21/xiaobing.txt "Static size_tread_callback (void *ptr, size_t s  ize, size_t nmemb, void *stream) {curl_off_t nread; /* In real-world cases, this would probablyget this data differently as this fread () stuff are exactly what thelibrary   Already would do by default internally */size_t Retcode = Fread (ptr, size, nmemb, (file*) stream);   Nread = (curl_off_t) retcode;  fprintf (stderr, "* * * We read%" curl_format_curl_off_t "bytes from file\n", nread); return retcode;}  int main (int argc,char **argv) {CURL *pcurlhandle;  Curlcode Res;  FILE *hd_src;  struct stat file_info;    curl_off_t fsize; /*1. Gets the size of the file to be uploaded */if (stat (Local_file, &file_info)) {printf ("Couldnt open '%s ':%s\n", Local_fiLE, Strerror (errno));  return 1;   } fsize = (curl_off_t) file_info.st_size;   printf ("Local File size:%" curl_format_curl_off_t "bytes.\n", fsize); /*2.   Gets the descriptive descriptor of the file to be uploaded */hd_src = fopen (Local_file, "RB"); /*3.   Initialize all possible calls */Curl_global_init (Curl_global_all); /*4.  Create a curlhandle*/Pcurlhandle = Curl_easy_init ();         if (curl) {/*5. Set a callback function */curl_easy_setopt (Pcurlhandle, curlopt_readfunction, Read_callback);         /*6. Enable upload flag bit */curl_easy_setopt (Pcurlhandle, Curlopt_upload, 1L);         /*7. Specify the URL of the Ftpserver */curl_easy_setopt (Pcurlhandle,curlopt_url, Remote_url);         /*8. Specify the file to be uploaded */curl_easy_setopt (Pcurlhandle, Curlopt_readdata, HD_SRC); /*9. Set the size of the file to be uploaded, which is noted above: when the number of references is curlopt_infilesize_large. The size type should be curl_off_t, and when the number of references is curlopt_infilesize, size should be a long type */curl_easy_setopt (Pcurlhandle, Curlopt_infilesize_        LARGE, (curl_off_t) fsize); /*10. Start to run our method of setting above */res= Curl_easy_perform (pcurlhandle); /*11. Check whether the run succeeds */if (res! = CURLE_OK) fprintf (stderr, "Curl_easy_perform () failed:%s\n", Curl_easy_stre     Rror (res)); /*12.    Close pcurlhandle*/Curl_easy_cleanup (pcurlhandle); } fclose (HD_SRC); /* Close the local file *//*13.  Clear all possible calls */Curl_global_cleanup (); return 0;}

The above program is the line to implement FTP upload files


3. Finally, consider a TFP download example:

/************************************************************************************* * * File name: TfpcurlDown LOAD.C * Function: Curl Test program * * Author: http://blog.csdn.net/King_BingGe * * created on: 201 4 September 29 * * Last Modification time: September 29, 2014 * * Specific: no * ********************************************************** /#include <stdio.h> #include <string.h> #include <curl/curl.h># Include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <  unistd.h> #define REMOTE_URL "ftp://172.30.26.247:21/xiao.txt" typedef struct FTPFILE {const char *filename; FILE *stream;} Cftpfile;static size_t write_callback (void *ptr, size_t size, size_t nmemb, void *stream) {cftpfile *out = (Cftpfile*) str  Eam        if (out &&!out->stream) {out->stream = fopen (Out->filename, "WB"); if (!out->stream) {PrinTF ("Write_callback failed \ n");        return-1; }} return Fwrite (PTR, size, nmemb, out->stream);}  int main (int argc, char **argv) {CURL *pcurlhandle;  Curlcode Res;   curl_off_t fsize;  Cftpfile ftpfile = {"/tmp/xiaoxiao.txt", NULL}; /*3.  Initialize all possible calls */Curl_global_init (Curl_global_all); /*4.  Create a curlhandle*/Pcurlhandle = Curl_easy_init ();    if (pcurlhandle) {/*5. Set a callback function */curl_easy_setopt (Pcurlhandle, curlopt_writefunction, Write_callback); /*7.    Specify the URL of the Ftpserver */curl_easy_setopt (Pcurlhandle,curlopt_url, Remote_url); /*8.    Specify the file to be uploaded */curl_easy_setopt (Pcurlhandle, Curlopt_userpwd, "cdn_ftp:123456"); /*9.    Specify the file to be uploaded */curl_easy_setopt (Pcurlhandle, Curlopt_writedata, &ftpfile); /*10. Sets the size of the file to be downloaded.    This size is the note obtained above: when the number of references is curlopt_infilesize_large, size type should be curl_off_t. When the number of references is curlopt_infilesize, size should be a long type of */curl_easy_setopt (Pcurlhandle, Curlopt_infilesize_large, (    curl_off_t) fsize); /*11. StartStart with the method we set above */Res = curl_easy_perform (pcurlhandle); /*12. Check whether the run succeeds */if (res! = CURLE_OK) fprintf (stderr, "Curl_easy_perform () failed:%s\n", Curl_easy_strerro    R (Res)); /*13.  Close pcurlhandle*/Curl_easy_cleanup (pcurlhandle);  } else {printf ("Curl_easy_init failed \ n"); }/*14.  Clear all possible calls */Curl_global_cleanup (); return 0;}




Libcurl Initial implementation of TFP upload and download functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.