libcurl库 ftp上传文件到服务器

来源:互联网 发布:网络dns错误是什么原因 编辑:程序博客网 时间:2024/06/05 07:12


libcurl主要功能就是用不同的协议连接和沟通不同的服务器。libcurl当前支持http, https, ftp, gopher, telnet, dict, file, 和ldap 协议。

今天主要是记录项目中libcurl ftp的使用,关于libcurl的API描述,这个链接已经描述的很详细了:https://curl.haxx.se/libcurl/c/allfuncs.html


以下代码在项目中学习到的,毕竟是小白只能修修补补,二手码农

用例如下:

/***************************************************************************** 函 数 名  : pkt_ftp_send 功能描述  : ftp发送文件 输入参数  : char *user    ftp服务器用户名                         char *passwd  ftp服务器密码                         char*dir      发送文件所在目录,注意目录后有"/",如 "/tmp/path/"                         char *file     待发送文件名            输出参数  : 无 返 回 值  :  调用函数  :  被调函数  :   修改历史      :  1.日    期   : xxxx    作    者   : xxx    修改内容   : 新生成函数*****************************************************************************/INT32 pkt_ftp_send(char *user, char *passwd,  char*dir, char *file){    CURLcode result;    long ulFileSize;    FILE*fp = NULL;    char acUserPwd[128] = "";    char acFtpForm[256] = "";    struct in_addr stIp;     char acIp[32];    UINT16 usPort;    char fileName[256] = "";    /* 获取服务器IP&PORT */    stIp.s_addr = 0xc0a801f9;       /* 缺省服务器IP地址 192.168.1.249 */     if(inet_ntop(AF_INET, (void *)&stIp, acIp, (socklen_t )sizeof(acIp)) == 0) {        return;    }        usPort = 2121;         /* 读取文件 */    snprintf(fileName, sizeof(fileName),"%s%s", dir, file);    fp = fopen(fileName, "r");    if(NULL == fp)    {         return -1;    }    fseek(fp, 0L, SEEK_END);    ulFileSize = ftell(fp);    fseek(fp, 0L, SEEK_SET);    /* 初始化CURL指针 */    CURL* curl = curl_easy_init();    if(NULL == curl)    {        fclose(fp);        return -1;    }          snprintf(acUserPwd, 128, "%s:%s", user, passwd);    snprintf(acFtpForm, 128, "ftp://%s:%u/%s", acIp, usPort, file);    curl_easy_setopt(curl, CURLOPT_USERPWD, acUserPwd);    curl_easy_setopt(curl, CURLOPT_URL, acFtpForm);    curl_easy_setopt(curl, CURLOPT_READDATA, fp);    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);    curl_easy_setopt(curl, CURLOPT_INFILESIZE, ulFileSize);    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60);    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);           result = curl_easy_perform(curl);    if(CURLE_OK!=result)    {           curl_easy_cleanup(curl);        fclose(fp);        return -1;    }     curl_easy_cleanup(curl);      fclose(fp);    return 0; }















原创粉丝点击