Sample code for 30+ languages & platforms
Unicode C++

Set a Remote File's Owner and Group

See more SFTP Examples

Demonstrates the Chilkat SFtp.SetOwnerAndGroup method, which sets the owner and group of a remote item. The arguments are the remote path (or handle), whether the first argument is a handle, and the new owner and group values.

Background: This is the SFTP equivalent of chown. Changing ownership is a privileged operation on Unix systems — ordinary users generally cannot give their files away — so expect it to fail unless the authenticated account has the necessary rights. It is most often used by administrative jobs that upload files which must then belong to a service account, such as a web server user.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkSFtpW.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Demonstrates the SFtp.SetOwnerAndGroup method, which sets the owner and group of a remote item.
    //  The 1st argument is the remote path (or handle), the 2nd (isHandle) indicates which, and the
    //  3rd and 4th are the new owner and group.

    CkSFtpW sftp;

    //  Connect, authenticate, and initialize the SFTP subsystem.
    int port = 22;
    success = sftp.Connect(L"sftp.example.com",port);
    if (success == false) {
        wprintf(L"%s\n",sftp.lastErrorText());
        return;
    }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    const wchar_t *password = L"mySshPassword";

    success = sftp.AuthenticatePw(L"mySshLogin",password);
    if (success == false) {
        wprintf(L"%s\n",sftp.lastErrorText());
        return;
    }

    success = sftp.InitializeSftp();
    if (success == false) {
        wprintf(L"%s\n",sftp.lastErrorText());
        return;
    }

    //  The 1st argument is a path, so isHandle is false.  Changing ownership typically requires
    //  elevated privileges on the server.
    bool isHandle = false;
    success = sftp.SetOwnerAndGroup(L"subdir/report.pdf",isHandle,L"www-data",L"www-data");
    if (success == false) {
        wprintf(L"%s\n",sftp.lastErrorText());
        return;
    }

    wprintf(L"Owner and group set.\n");

    sftp.Disconnect();
    }