curl 实现sftp功能

1. .h文件

#include
#include
#include
#pragma comment(lib,"libcurl_imp.lib")
#undef DISABLE_SSH_AGENT

int            get_file_size        (FILE *file);
bool        SftpUpload            (std::string strSourceFilePath, std::string strSftpFilePath, int iPort, tstring &strError, int &iError);


2..cpp文件

static size_t read_callback(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
	size_t retcode;
	curl_off_t nread;
	retcode = fread(ptr, size, nmemb, stream);
	nread = (curl_off_t)retcode;
	fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T " bytes from file\n", nread);
	return retcode;
}

int CSftp::get_file_size(FILE *file)
{
	int size = 0;
	fseek(file, 0L, SEEK_END);
	size = ftell(file);
	fseek(file, 0L, SEEK_SET);
	return size;
}

//strSourceFilePath 要上传的文件的文件路径
//strSftpFilePath sftp的上传路径 sftp://username:passwors@ip/path/file.txt
//iport 端口
//strError 返回错误信息
bool CSftp::SftpUpload(std::string strSourceFilePath, std::string strSftpFilePath, int iPort, tstring &strError, int &iError)
{
	bool bError = true;
	CURL* curl;
	CURLcode res;
	const char *sourcePath = strSourceFilePath.c_str();
	const char *sftpPath = strSftpFilePath.c_str();
	FILE* file = fopen(sourcePath, "rb");
	curl_global_init(CURL_GLOBAL_ALL);
	curl = curl_easy_init();
	if(curl) {
		curl_easy_setopt(curl, CURLOPT_URL,sftpPath);
		curl_easy_setopt(curl, CURLOPT_PORT, iPort);
		curl_easy_setopt(curl, CURLOPT_READFUNCTION,read_callback);
		curl_easy_setopt(curl, CURLOPT_READDATA,file);
		curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,get_file_size(file));
		curl_easy_setopt(curl, CURLOPT_FTP_RESPONSE_TIMEOUT,120);
#ifndef DISABLE_SSH_AGENT
		curl_easy_setopt(curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);
#endif
		curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 1L);
		curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
		res = curl_easy_perform(curl);
		curl_easy_cleanup(curl);

		if(CURLE_OK != res) {
			fprintf(stderr, "curl told us %d\n", res);
			bError = false;
			GetErrorInfo(res, strError);
			iError = res;
		}
	}
	fclose(file); 
	curl_global_cleanup();
	return bError;
}

void CSftp::GetErrorInfo (int resId, std::wstring & strError)
{
    switch (resId)
    {
    case CURLE_COULDNT_CONNECT:
        strError = _T("couldn't connect");
        break;
    case CURLE_LOGIN_DENIED:
        strError = _T("user, password or similar was not accepted and we failed to login.");
        break;
    case CURLE_REMOTE_FILE_NOT_FOUND:
        strError = _T("remote file not found");
        break;
    case CURLE_COULDNT_RESOLVE_HOST:
        strError = _T("couldn't resolve host");
        break;
    default:
        strError = resId;
        break;
    }

} 

实例地址:

http://download.csdn.net/detail/leftstrang/9632264


你可能感兴趣的:(curl 实现sftp功能)