Chilkat Event Callbacks in C++

Here’s a complete C++ example using the Chilkat C++ library to perform an SFTP download with support for the following event callbacks:

  • PercentDone — to track download progress
  • AbortCheck — to allow canceling the operation
  • ProgressInfo — to monitor additional info such as transfer rate

While this example focuses on callbacks for an SFTP download, the same method applies to other Chilkat C++ classes like Http, Ftp2, MailMan, and Rest.


1. Create a Class that Inherits from CkBaseProgress


#include <CkSFtp.h>
#include <CkGlobal.h>
#include <CkBaseProgress.h>
#include <iostream>

class MyProgress : public CkBaseProgress {
public:
    bool Abort;

    MyProgress() : Abort(false) {} 

    // Called periodically with % done
    // Return true to abort.
    bool PercentDone(int pctDone) override {
        std::cout << "Progress: " << pctDone << "%\n";
        return Abort;
    }

    // Called periodically to allow user to cancel
    // Return true to abort.
    bool AbortCheck(void) override {
        return Abort;
    }

    // Called with other status messages
    void ProgressInfo(const char *name, const char *value) override {
        std::cout << "[ProgressInfo] " << name << ": " << value << "\n";
        return;
    }
};

2. Main Function to Connect and Download

int main() {
    CkGlobal glob;

    if (!glob.UnlockBundle("YOUR_CHILKAT_UNLOCK_CODE")) {
        std::cerr << "Unlock failed: " << glob.lastErrorText() << "\n";
        return 1;
    }

    CkSFtp sftp;

    bool success = sftp.Connect("sftp.example.com", 22);
    if (!success) {
        std::cerr << sftp.lastErrorText() << "\n";
        return 1;
    }

    success = sftp.AuthenticatePw("username", "password");
    if (!success) {
        std::cerr << sftp.lastErrorText() << "\n";
        return 1;
    }

    success = sftp.InitializeSftp();
    if (!success) {
        std::cerr << sftp.lastErrorText() << "\n";
        return 1;
    }

    MyProgress progress;
    sftp.put_EventCallbackObject(&progress);

    const char *remoteFile = "remote/path/file.txt";
    const char *localFile = "downloaded.txt";

    success = sftp.DownloadFileByName(remoteFile, localFile);
    if (!success) {
        std::cerr << sftp.lastErrorText() << "\n";
        return 1;
    }

    std::cout << "Download completed successfully.\n";

    return 0;
}

Notes

  • Replace YOUR_CHILKAT_UNLOCK_CODE with your actual license key or trial code.
  • This example uses password authentication; modify if using public key authentication.
  • PercentDone is only called if the SFTP library can determine total size (for large files).
  • You can trigger cancellation by setting progress.Abort = true; from another thread.