Source Code File 05-02_ftpmemory.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

/* memory buffer structure */
struct data_chunk {
    char *buf;
    size_t size;
};

static size_t read_callback(
    void *ptr,
    size_t size,
    size_t nmemb,
    void *user_data)
{
    struct data_chunk *upload;
    size_t max;
    
    /* initialize local pointer */
    upload = (struct data_chunk *)user_data;
    /* calculate number of bytes to write */
    max = size*nmemb;
    
    /* if nothing to write, return zero */
    if(max<1)
        return(0);
    
    /* move the data chunk into buffer */
    if(upload->size)
    {
        if(max > upload->size)
            max = upload->size;
        memcpy(ptr, upload->buf,max);
        /* increase the pointer's base to
           reference the next chunk */
        upload->buf += max;
        /* adjust the buffer size */
        upload->size -= max;

        return(max);
    }
    
    return(0);
}

int main()
{
    char ftp_upload[] = "ftp://127.0.0.0/test.txt";
    char user_pass[] = "username:password";
    char text[] = "This text is uploaded\n";
    CURL *curl;
    CURLcode res;
    struct data_chunk ftp;
    int bufsize;

    bufsize = strlen(text) + 1;
    /* initialize the memory buffer */
    ftp.buf = text;
    ftp.size = bufsize;

    /* initialize curl */
    curl = curl_easy_init();
    
    puts("Preparing FTP...");
    /* set options for FPT upload */
    curl_easy_setopt(curl,
        CURLOPT_URL, ftp_upload);
    curl_easy_setopt(curl,
        CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl,
        CURLOPT_USERPWD, user_pass);
    curl_easy_setopt(curl,
        CURLOPT_UPLOAD, 1L);
    curl_easy_setopt(curl,
        CURLOPT_READFUNCTION, read_callback);
    curl_easy_setopt(curl,
        CURLOPT_READDATA, &ftp.buf);
    curl_easy_setopt(curl,
        CURLOPT_INFILESIZE, ftp.size);
    
    /* request-send upload */
    res = curl_easy_perform(curl);
    if( res!=CURLE_OK )
    {
        fprintf(stderr,
            "curl FTP upload fail: %s\n",
            curl_easy_strerror(res));
        exit(1);
    }

    /* cleanup */
    curl_easy_cleanup(curl);
    /* inform the user */
    puts("FTP upload complete");
    
    return(0);
}

Notes

* The ftp_upload[] string in the main() function is a placeholder. It works if you have an FTP server on your computer, providing the file named also exists.

* Wide version of this code (statements not split)