libcurl使用sftp上传文件

1.程序代码

#include 
#include 
#include 
#include 
#include 

#undef DISABLE_SSH_AGENT

struct LocalFile {
        struct stat file_info;
        char filename[256];
        FILE *stream;
};

static size_t my_fread(void *buffer, size_t size, size_t nmemb, void *stream)
{
        struct LocalFile *out = (struct LocalFile *)stream;

        if(!out->stream)
        {
                out->stream = fopen(out->filename, "rb");
                if(!out->stream)
                        return -1;
        }

        return fread(buffer, size, nmemb, out->stream);
}

int main()
{
        CURL *curl;
        CURLcode res;
        struct LocalFile localfile;
        curl_off_t fsize;

        memset(&localfile, 0x00, sizeof(localfile));
        strcpy(localfile.filename, "1.txt");

        if(stat(localfile.filename,&(localfile.file_info)))
        {
                printf("couldnt open %s\n", localfile.filename);
                return -1;
        }

        fsize = (curl_off_t)localfile.file_info.st_size;

        curl_global_init(CURL_GLOBAL_DEFAULT);

        curl = curl_easy_init();

        if(curl)
        {
                curl_easy_setopt(curl, CURLOPT_URL, "sftp://[email protected]/home/freetype/src/5/1.txt");

                curl_easy_setopt(curl, CURLOPT_READFUNCTION, my_fread);

                curl_easy_setopt(curl, CURLOPT_READDATA, &localfile);

                curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE,(curl_off_t)fsize);

                curl_easy_setopt(curl,CURLOPT_UPLOAD,1L);

#ifndef DISABLE_SSH_AGENT
                curl_easy_setopt(curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);
                curl_easy_setopt(curl, CURLOPT_PASSWORD, "freetype");
#endif

                curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); //0去掉调试信息, 1添加调试信息

                res = curl_easy_perform(curl);

                curl_easy_cleanup(curl);

                if(CURLE_OK != res)
                {
                        fprintf(stderr, "curl told us %d\n", res);
                }
        }

        if(localfile.stream)
                fclose(localfile.stream);

        curl_global_cleanup();

        return 0;
}

2.编译代码

$ gcc -o sftpput sftpput.c -I$HOME/local/include/ -lcurl

3.运行程序

$ ./sftpput

你可能感兴趣的:(libcurl使用sftp上传文件)