Skip to content
Search

Libcurl

lastmod 2020-07-09created 2014-08-286 edits

Notes on the C API of cURL.

Catching error messages

When running it by calling popen() from C source, you can catch error messages by adding redirect characters as follows.

snprintf(cmd, sizeof(cmd), "curl -T \"%s\" -u \"%s:%s\" ftp://%s:%d/%s/ -s -S -m %d --connect-timeout %d --ftp-create-dirs 2>&1",
        src_file, userid, passwd,
        ipaddr, port, dst_dir,
        timeout, conn_timeout);

fp = popen(cmd, "r");
if(fp == NULL) {
    LOG_ERR("%s:: popen() fail: errno=%d(%s)\n",
            _func_, errno, strerror(errno));
    return -1;
}
while(fgets(buff, sizeof(buff), fp) != NULL) {
    LOG_ERR("%s:: ftp upload error: err=%s", _func_, buff);
    success_flag = 0;
    break;
}
pclose(fp);

Thread safety

/* This is the callback executed when a new threads starts */
static void *pull_one_url(void *url)
{
  CURL *curl;

  curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_URL, url);
  curl_easy_perform(curl); /* ignores error */ 
  curl_easy_cleanup(curl);

  return NULL;
}

/* ... */

/* This is the main loop that creates `NUMT` threads for parallel fetching */
for(i=0; i< NUMT; i++) {
    error = pthread_create(&tid[i],
                           NULL, /* default attributes please */ 
                           pull_one_url,
                           (void *)urls[i]);
  /* ... */
}

Searching FTP sites

Finds file names on an FTP site that match a given string (or regular expression).

Usage

curl_ftpdir [-s "string or expression"] [-u userid:password] [-a] [-l] [-g] <FTP URL>

Following standard Unix command-line syntax, [] brackets are optional fields, and <> or no brackets are required fields. In other words, it works with at least just the FTP URL.

-s "string or expression"
The exact file name or regular expression to search for under the given FTP URL. Regular expressions support the POSIX standard format.
-u userid:password
The user name and password used to connect to the FTP site, entered in the form userid:password with a colon as the separator.
Without this option, it connects as Anonymous (anonymous FTP).
-a
Prints only matched files. By default, this utility shows all file names at the FTP URL and highlights only the matched file names in bright yellow to distinguish them. With this option, however, it shows only the file names matched by the search option (-s ...) and hides the remaining unmatched files.
-l
Turns off highlighting. Output does not use ANSI colors.
-g
Enables debugging. Shows how the FTP commands work during operation, and at the end also shows the list of subdirectories of the searched URL.

See also

Favorite site

How to build libcurl

author Zer0 sitemap