Preliminary realization of Libcurl TFP upload and download function

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


The goal of this learning note is to use Libcurl to implement FTP file upload and download functions.

A brief introduction of Libcurlde

Libcurl is a free and easy-to-use library that uses 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. Agents, 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 one. High-speed, such excuses are mainly used 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, by using curl_easy_setopt () to set the full range of options, the most important of these parameters is the URL, at the same time you also most likely need to set some callback functions. These callback functions will be called when the condition is met.

3, when the above work is done, you can use Curl_easy_perform () to notify the Libcurl file transfer, the function of the entire transmission process is complete or failed to return a value.

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

The following five steps are for these. Write an instance to test

Iv. Introduction to some function functions

1, CURL *curl_easy_init ();

The function must be called first. A curl* type of handle will be returned. And the function will be used in conjunction with Curl_easy_cleanup ().

Increased initialization error. The function will return a null.

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. Will change the function of Libcurl, this need to carefully read the guidance document, once set the way 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, once the function is run. Will notify Libcurl to run all of the methods we set previously, 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. Since the above URL has been redirected, it is 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 sample is a simple example of a visit to the Web page, the following continue to learn an FTP upload sample

#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. This size is the note obtained above: when the number of participants is curlopt_infilesize_large.      The size type should be curl_off_t.                       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. Set the size of the file to be downloaded, this size is the note above: When the reference is Curlopt_infilesize_large, the size type should be curl_off_t, when the number of references is Curlopt_ Infilesize the size should be a long type */curl_easy_setopt (Pcurlhandle, Curlopt_infilesize_large, (curl_off_t) F    size); /*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;}




Preliminary realization of Libcurl TFP upload and download function

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.