您的位置:首页 > 编程语言 > PHP开发

sftp协议通过调用libcurl库实现文件的上传

2017-09-08 17:00 260 查看
#include <stdio.h>

#include <stdlib.h>

#include <curl.h>

#undef DISABLE_SSH_AGENT

size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
 //回调函数

{
curl_off_t nread;
size_t retcode = fread(ptr, size, nmemb, (FILE*)(stream));
nread = (curl_off_t)retcode;
return retcode;

}

int main(void)

{
CURL *curl;
CURLcode res;
const char* urlkey = "用户名:密码"; //服务器用户名密码
FILE* pSendFile = fopen("本地文件路径", "rb");
fseek(pSendFile, 0L, SEEK_END);
size_t iFileSize = ftell(pSendFile);
fseek(pSendFile, 0L, SEEK_SET);

curl_global_init(CURL_GLOBAL_DEFAULT);

curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL,
"sftp://服务器IP地址/服务器端的文件路径");
curl_easy_setopt(curl, CURLOPT_USERPWD,urlkey);  
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
curl_easy_setopt(curl, CURLOPT_READDATA, pSendFile);
curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 0);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
curl_easy_setopt(curl, CURLOPT_INFILESIZE, iFileSize);

#ifndef DISABLE_SSH_AGENT
curl_easy_setopt(curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);

#endif
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

res = curl_easy_perform(curl);

curl_easy_cleanup(curl);

if(CURLE_OK != res) 

{

fprintf(stderr, "curl told us %d\n", res);
}

}

fclose(pSendFile);
curl_global_cleanup();

  return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: